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 :

# 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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/lambda/python-lambda-exercise-47.php