Sorting Methods in Python
1. Using sort() Method
The sort() method sorts a list in place (modifies the original list) in ascending order. You
can use reverse=True to sort in descending order.
Example:
numbers = [5, 2, 8, 1, 3]
[Link]()
print(numbers) # Output: [1, 2, 3, 5, 8]
[Link](reverse=True)
print(numbers) # Output: [8, 5, 3, 2, 1]
2. Using sorted() Function
The sorted() function returns a new sorted list without modifying the original list.
Example:
numbers = [5, 2, 8, 1, 3]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 5, 8]
print(numbers) # Original list remains unchanged
What are Tuples?
A tuple is an immutable (unchangeable) ordered collection of elements. Tuples are defined
using parentheses (). Since tuples cannot be modified, they are faster than lists.
Example:
my_tuple = (10, 20, 30, 'apple')
print(my_tuple) # Output: (10, 20, 30, 'apple')
Difference Between Lists and Tuples
Lists are mutable (can be changed), while tuples are immutable (cannot be changed). Lists
are defined using square brackets [], while tuples use parentheses ().
What are Dictionaries?
A dictionary is a collection of key-value pairs. Dictionaries are defined using curly brackets
{}. Each key is unique, and values can be modified.
Example:
student = {"name": "Alice", "age": 20, "grade": "A"}
print(student["name"]) # Output: Alice