This chapter delves into the various data structures available in Python, including lists, tuples, sets, and dictionaries. These structures are fundamental for organizing and manipulating data efficiently.
Lists
Lists are one of the most commonly used data structures in Python. They are ordered and mutable, which means you can change their elements and add or remove items from them.
- Accessing Elements: You can access elements in a list by their index. For example,
my_list[0]
will give you the first element. - Slicing: Lists support slicing, which allows you to extract a portion of the list. For example,
my_list[1:3]
will give you the second and third elements.
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # Output: 1
print(my_list[1:4]) # Output: [2, 3, 4]
Tuples
Tuples are similar to lists, but they are immutable. This means you cannot change their elements once they are created.
- Creating Tuples: You can create a tuple by enclosing elements in parentheses. For example,
(1, 2, 3)
.
my_tuple = (1, 2, 3)
print(my_tuple[1]) # Output: 2
Sets
Sets are unordered collections of unique elements. They are useful for operations like set theory (union, intersection, difference).
- Creating Sets: You can create a set by enclosing elements in curly braces. For example,
{1, 2, 3}
.
my_set = {1, 2, 3}
print(my_set) # Output: {1, 2, 3}
Dictionaries
Dictionaries are key-value pairs. They are used to store data in a structured way, making it easy to access values based on their keys.
- Creating Dictionaries: You can create a dictionary by enclosing key-value pairs in curly braces. For example,
{name: 'John', age: 30}
.
my_dict = {'name': 'John', 'age': 30}
print(my_dict['name']) # Output: John
Further Reading
For more information on Python data structures, you can refer to the following resources: