sort a list in python
- User
sort a list in python
Assistant
python
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
sort a list in python
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
# 1. Using the sort() method:
# Create a list of unsorted numbers
numbers = [5, 2, 1, 7, 4]
# Sort the list in ascending order using the sort() method
numbers.sort()
# Print the sorted list
print(numbers) # Output: [1, 2, 4, 5, 7]
# 2. Using the sorted() function:
# Create a list of unsorted numbers
numbers = [5, 2, 1, 7, 4]
# Sort the list in ascending order using the sorted() function
sorted_numbers = sorted(numbers)
# Print the sorted list
print(sorted_numbers) # Output: [1, 2, 4, 5, 7]
# 3. Sort a list of strings:
# Create a list of unsorted strings
strings = ["apple", "banana", "cherry", "dog", "elephant"]
# Sort the list in alphabetical order using the sort() method
strings.sort()
# Print the sorted list
print(strings) # Output: ['apple', 'banana', 'cherry', 'dog', 'elephant']
# 4. Sort a list of dictionaries:
# Create a list of dictionaries with different keys and values
people = [
{"name": "John", "age": 30},
{"name": "Mary", "age": 25},
{"name": "Bob", "age": 40},
]
# Sort the list of dictionaries by age using the sorted() function and a lambda function
sorted_people = sorted(people, key=lambda person: person["age"])
# Print the sorted list of dictionaries
print(sorted_people) # Output: [{'name': 'Mary', 'age': 25}, {'name': 'John', 'age': 30}, {'name': 'Bob', 'age': 40}]
# 5. Sort a list of objects:
# Create a class with a name and age attribute
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Create a list of Person objects
people = [
Person("John", 30),
Person("Mary", 25),
Person("Bob", 40),
]
# Sort the list of Person objects by age using the sorted() function and a lambda function
sorted_people = sorted(people, key=lambda person: person.age)
# Print the sorted list of Person objects
print(sorted_people) # Output: [Person(name='Mary', age=25), Person(name='John', age=30), Person(name='Bob', age=40)]