class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Create instances of Person
people = [Person('Alice', 30), Person('Bob', 25), Person('Charlie', 35)]
# Sort people by age using a lambda function as the key
sorted_people = sorted(people, key=lambda x: x.age)Sort List of Objects by Attribute in Python
python
Related Posts
More content you might like
Code
javascript
Sorting an Array in JavaScript
No preview available for this content.
Jan 26, 2024
Read More Code
javascript
Sorting an Array
// Array of numbers
const numbers = [4, 2, 8, 1, 6];
// Sorting the array in ascending order
const sortedNumbers = numbers.sort((a, b) => a - b);
// Logging the sorted array
console.log('Sorted Array:', sortedNumbers);Jan 26, 2024
Read More Code
python
Sorting a Dictionary by Values
No preview available for this content.
Jan 26, 2024
Read More Code
python
Sort a List
The following Python code demonstrates how to sort a list of fruits alphabetically using the sort() method:
# Define a list of fruits
fruits = ['apple', 'banana', 'cherry', 'date', 'fig']
# Sort the list alphabetically
fruits.sort()
print('Sorted Fruits:', fruits)Jan 26, 2024
Read MoreDiscussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!