1. Lists:
A list is a mutable, ordered collection of elements. Lists are defined using square brackets []
.
# Example of a list
fruits = ["apple", "banana", "orange"]
1.1 Common Operations on Lists:
- Accessing Elements:
first_fruit = fruits[0]
- Slicing:
sliced_fruits = fruits[1:3]
- Appending:
fruits.append("grape")
- Removing:
fruits.remove("banana")
2. Tuples:
A tuple is an immutable, ordered collection of elements. Tuples are defined using parentheses ()
.
# Example of a tuple
coordinates = (3, 4)
2.1 Common Operations on Tuples:
- Accessing Elements:
x = coordinates[0]
- Unpacking:
x, y = coordinates
3. Sets:
A set is an unordered collection of unique elements. Sets are defined using curly braces {}
.
# Example of a set
colors = {"red", "green", "blue"}
3.1 Common Operations on Sets:
- Adding Elements:
colors.add("yellow")
- Removing Elements:
colors.remove("green")
- Set Operations:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
intersection_set = set1.intersection(set2)
difference_set = set1.difference(set2)
4. Choosing Between Lists, Tuples, and Sets:
- Lists: Use lists when you need a mutable, ordered collection and need to perform operations like adding or removing elements.
- Tuples: Use tuples when you have a collection of elements that should remain constant throughout the program and do not need to be modified.
- Sets: Use sets when you need an unordered collection of unique elements and want to perform set operations like union, intersection, or difference.
5. Immutable vs. Mutable:
- Lists are mutable, meaning you can modify their elements after creation.
- Tuples are immutable, meaning their elements cannot be modified after creation.
- Sets are mutable, but individual elements cannot be modified. You can add or remove elements.
6. Common Use Cases:
- Lists: Ideal for collections of items where the order matters and you need the ability to modify the elements.
- Tuples: Suitable for representing fixed collections of elements, such as coordinates or configurations.
- Sets: Useful for tasks that involve mathematical set operations or when you need a collection of unique elements.
7. Conclusion:
Lists, tuples, and sets are fundamental data structures in Python, each serving different purposes. Choosing the right data structure depends on the requirements of your program, including the need for mutability, order, and uniqueness.
In the next sections, we’ll explore more advanced topics and practical applications of data structures in Python.