w3resource

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


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 :

# Define a function 'sort_mixed_list' that sorts a mixed list of integers and strings
def sort_mixed_list(mixed_list):
    # Sort the 'mixed_list' using the 'sort' method with a key function
    # The key function first checks if an element is a string (True for string, False for integer) and then sorts accordingly
    mixed_list.sort(key=lambda e: (isinstance(e, str), e))
    
    # Return the sorted mixed list
    return mixed_list

# Create a mixed list containing integers and strings
mixed_list = [19, 'red', 12, 'green', 'blue', 10, 'white', 'green', 1]

# Print the original mixed list
print("Original list:")
print(mixed_list)

# Sort the mixed list using the 'sort_mixed_list' function and print the sorted result
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']

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 Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.