📊 Organizing Lists
Organizing lists is essential for data management and presentation. Python provides powerful built-in methods to sort, reverse, and arrange list elements in various ways. Whether you need alphabetical order, numerical sorting, or custom arrangements, understanding these techniques will help you present data clearly and efficiently.
Proper list organization makes data easier to read, search, and process, which is crucial for data analysis and user interfaces.
# Basic list organization examples
numbers = [64, 34, 25, 12, 22, 11, 90]
names = ["Charlie", "Alice", "Bob", "Diana"]
print("Original numbers:", numbers)
print("Sorted numbers:", sorted(numbers))
print("Original names:", names)
print("Sorted names:", sorted(names))
# Reverse a list
print("Reversed numbers:", numbers[::-1])
🔢 Sorting Lists with sort()
The sort()
method sorts a list in place, meaning it modifies the original list. This method is efficient and convenient when you want to permanently change the list order.
Basic Sorting
# Basic sorting with sort()
numbers = [64, 34, 25, 12, 22, 11, 90]
print("Original:", numbers)
numbers.sort()
print("After sort():", numbers)
Sorting Strings
# Sorting strings alphabetically
fruits = ["banana", "apple", "cherry", "date"]
print("Original fruits:", fruits)
fruits.sort()
print("Sorted fruits:", fruits)
Reverse Sorting
# Sorting in descending order
scores = [85, 92, 78, 96, 88]
print("Original scores:", scores)
scores.sort(reverse=True)
print("Sorted descending:", scores)
Case-Insensitive Sorting
# Case-insensitive string sorting
names = ["alice", "Bob", "Charlie", "diana"]
print("Original names:", names)
names.sort(key=str.lower)
print("Case-insensitive sort:", names)
🎯 Using sorted() Function
The sorted()
function creates a new sorted list without modifying the original. This is useful when you need both the original and sorted versions of your data.
Basic sorted() Usage
# Using sorted() function
original = [64, 34, 25, 12, 22, 11, 90]
print("Original list:", original)
sorted_list = sorted(original)
print("Sorted copy:", sorted_list)
print("Original unchanged:", original)
Sorting Different Data Types
# Sorting different types
words = ["python", "java", "c++", "javascript"]
print("Original words:", words)
sorted_words = sorted(words)
print("Sorted words:", sorted_words)
# Sorting by length
sorted_by_length = sorted(words, key=len)
print("Sorted by length:", sorted_by_length)
🔄 Reversing Lists
Python provides multiple ways to reverse lists, each suited for different scenarios. You can reverse in place or create a reversed copy.
Using reverse() Method
# Using reverse() method (modifies original)
numbers = [1, 2, 3, 4, 5]
print("Original:", numbers)
numbers.reverse()
print("After reverse():", numbers)
Using Slicing for Reversal
# Using slicing (creates new list)
colors = ["red", "green", "blue", "yellow"]
print("Original colors:", colors)
reversed_colors = colors[::-1]
print("Reversed copy:", reversed_colors)
print("Original unchanged:", colors)
🎨 Custom Sorting with Key Functions
Custom sorting allows you to sort lists based on specific criteria using key functions. This powerful feature enables complex sorting scenarios.
Sorting by String Length
# Sorting by string length
words = ["cat", "elephant", "dog", "hippopotamus"]
print("Original words:", words)
by_length = sorted(words, key=len)
print("Sorted by length:", by_length)
# Longest first
longest_first = sorted(words, key=len, reverse=True)
print("Longest first:", longest_first)
Sorting Nested Lists
# Sorting lists of lists
students = [["Alice", 85], ["Bob", 92], ["Charlie", 78]]
print("Original students:", students)
# Sort by grade (second element)
by_grade = sorted(students, key=lambda x: x[1])
print("Sorted by grade:", by_grade)
# Sort by name (first element)
by_name = sorted(students, key=lambda x: x[0])
print("Sorted by name:", by_name)
Sorting with Multiple Criteria
# Sorting with multiple criteria
people = [("Alice", 25, 85), ("Bob", 30, 92), ("Charlie", 25, 78)]
print("Original people:", people)
# Sort by age, then by score
by_age_score = sorted(people, key=lambda x: (x[1], x[2]))
print("By age, then score:", by_age_score)
🏗️ Sorting Complex Data Structures
When working with complex data like dictionaries in lists, you need specialized sorting approaches.
Sorting Lists of Dictionaries
# Sorting lists of dictionaries
products = [
{"name": "laptop", "price": 999},
{"name": "mouse", "price": 25},
{"name": "keyboard", "price": 75}
]
print("Original products:")
for product in products:
print(f" {product}")
# Sort by price
by_price = sorted(products, key=lambda x: x["price"])
print("\nSorted by price:")
for product in by_price:
print(f" {product}")
Sorting by Multiple Dictionary Keys
# Sorting by multiple keys
employees = [
{"name": "Alice", "dept": "IT", "salary": 70000},
{"name": "Bob", "dept": "HR", "salary": 65000},
{"name": "Charlie", "dept": "IT", "salary": 75000}
]
# Sort by department, then by salary
by_dept_salary = sorted(employees, key=lambda x: (x["dept"], x["salary"]))
print("Sorted by dept, then salary:")
for emp in by_dept_salary:
print(f" {emp['name']}: {emp['dept']}, ${emp['salary']}")
Hands-on Exercise
Create a function that sorts a list of student records by grade (highest first), and for students with the same grade, sort by name alphabetically
def sort_students(students):
# TODO: Sort by grade (descending) then by name (ascending)
# Use a tuple in the key function: (-grade, name)
# TODO: Your code here
return sorted_students
# Test the function
student_list = [
("Charlie", 85),
("Alice", 92),
("Bob", 85),
("Diana", 92),
("Eve", 78)
]
print("Original students:", student_list)
sorted_students = sort_students(student_list)
print("Sorted students:", sorted_students)
Solution and Explanation 💡
Click to see the complete solution
def sort_students(students):
# Sort by grade (descending) then by name (ascending)
# Use negative grade for descending order, positive name for ascending
sorted_students = sorted(students, key=lambda x: (-x[1], x[0]))
return sorted_students
# Test the function
student_list = [
("Charlie", 85),
("Alice", 92),
("Bob", 85),
("Diana", 92),
("Eve", 78)
]
print("Original students:", student_list)
sorted_students = sort_students(student_list)
print("Sorted students:", sorted_students)
Key Learning Points:
- 📌 Multiple criteria: Use tuple in key function for multiple sort criteria
- 📌 Negative values: Use
-x[1]
to sort numbers in descending order - 📌 Lambda functions: Perfect for custom sorting logic
- 📌 Stable sorting: Python's sort is stable, maintaining relative order for equal elements
🎪 Common Organization Patterns
Alphabetical Organization
# Alphabetical organization
names = ["charlie", "Alice", "bob", "Diana"]
print("Original names:", names)
# Case-insensitive alphabetical
alphabetical = sorted(names, key=str.lower)
print("Alphabetical:", alphabetical)
Numerical Organization
# Numerical organization
scores = [85, 92, 78, 96, 88, 73, 91]
print("Original scores:", scores)
# Highest to lowest
highest_first = sorted(scores, reverse=True)
print("Highest first:", highest_first)
Priority Organization
# Priority-based organization
tasks = [
("Email client", "high"),
("Update website", "low"),
("Fix bug", "urgent"),
("Write docs", "medium")
]
priority_order = {"urgent": 1, "high": 2, "medium": 3, "low": 4}
by_priority = sorted(tasks, key=lambda x: priority_order[x[1]])
print("Tasks by priority:")
for task, priority in by_priority:
print(f" {task} ({priority})")
Learn more about for loops to understand how sorting and iteration work together in data processing.
Test Your Knowledge
Test what you've learned about organizing lists in Python:
What's Next?
Now that you know how to organize lists effectively, you're ready to learn about combining lists. This includes merging, joining, and various techniques for working with multiple lists together.
Ready to continue? Check out our lesson on Combining Lists.
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.