Data structures are used to store and organize data in Python. Some of the most commonly used data structures in Python are lists, tuples, and dictionaries.
Lists
A list is a collection of items that are ordered and changeable. Lists are defined using square brackets []
and can contain elements of different data types. Here’s an example:
fruits = ["apple", "banana", "cherry"]
You can access individual elements of a list using indexing. Indexing starts from 0 for the first element. Here’s how you can access elements of a list:
print(fruits[0])
# Output: apple
print(fruits[1])
# Output: banana
print(fruits[2])
# Output: cherry
Tuples
A tuple is a collection of items that are ordered and immutable (cannot be changed). Tuples are defined using parentheses ()
and can contain elements of different data types. Here’s an example:
colors = ("red", "green", "blue")
You can access individual elements of a tuple using indexing, similar to lists.
Dictionaries
A dictionary is a collection of key-value pairs that are unordered and changeable. Dictionaries are defined using curly braces {}
and consist of keys and their corresponding values. Here’s an example:
person = {"name": "Alice", "age": 30, "city": "New York"}
You can access the values of a dictionary using keys. Here’s how you can access values from the person
dictionary:
print(person["name"]) # Output: Alice
print(person["age"]) # Output: 30
print(person["city"]) # Output: New York
Understanding how to work with lists, tuples, and dictionaries is essential for handling and manipulating data in Python. In the next chapter, we’ll explore file handling, which allows you to read from and write to files on your computer.