w3resource

Python: Sort a given mixed list of integers and strings using lambda

Python Lambda: Exercise-47 with Solution

Write a Python program to sort a given mixed list of integers and strings using lambda. Numbers must be sorted before strings.

Sample Solution:

Python Code :

def sort_mixed_list(mixed_list):
    mixed_list.sort(key=lambda e: (isinstance(e, str), e))
    return mixed_list
mixed_list = [19,'red',12,'green','blue', 10,'white','green',1]
print("Original list:")
print(mixed_list)
print("\nSort the said  mixed list of integers and strings:")
print(sort_mixed_list(mixed_list))

Sample Output:

Original list:
[19, 'red', 12, 'green', 'blue', 10, 'white', 'green', 1]

Sort the said  mixed list of integers and strings:
[1, 10, 12, 19, 'blue', 'green', 'green', 'red', 'white']

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find index position and value of the maximum and minimum values in a given list of numbers using lambda.

Next: Write a Python program to sort a given list of strings(numbers) numerically using lambda.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Splits values into two groups. If an element in filter is True, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group

Example:

def tips_bifurcate(lst, filter):
  return [
    [x for i, x in enumerate(lst) if filter[i] == True],
    [x for i, x in enumerate(lst) if filter[i] == False]
  ]

print(tips_bifurcate(['little', 'boo', 'peep', 'sat'], [True, True, False, True]))

Output:

[['little', 'boo', 'sat'], ['peep']]