Lists

Lists are ordered collections of items, which can be of different data types. Lists are mutable, meaning their elements can be modified after creation.

fruits = ["apple", "banana", "cherry"]
print(fruits)             # Output: ['apple', 'banana', 'cherry']
fruits.append("orange")   # Adding an item to the list
print(fruits)             # Output: ['apple', 'banana', 'cherry', 'orange']
fruits[1] = "kiwi"        # Modifying an item in the list
print(fruits)             # Output: ['apple', 'kiwi', 'cherry', 'orange']

Tuples

Tuples are ordered collections of items, similar to lists. However, tuples are immutable, meaning their elements cannot be modified after creation.

point = (3, 4)
print(point)              # Output: (3, 4)
x, y = point              # Tuple unpacking
print(x, y)               # Output: 3 4
point = (3, 4, 5)         # Creating a new tuple
print(point)              # Output: (3, 4, 5)

Dictionaries

Dictionaries are unordered collections of key-value pairs. They are mutable and allow for efficient data retrieval and modification.

person = {"name": "Alice", "age": 25, "city": "New York"}
print(person)             # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
person["email"] = "[email protected]"  # Adding a new key-value pair
print(person)             # Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'email': '[email protected]'}
age = person.get("age")   # Retrieving a value by key
print(age)                # Output: 25

Copy code

Sets

Sets are unordered collections of unique elements. They are mutable, and elements can be added or removed from a set.

numbers = {1, 2, 3, 4, 5}
print(numbers)            # Output: {1, 2, 3, 4, 5}
numbers.add(6)            # Adding an element to the set
print(numbers)            # Output: {1, 2, 3, 4, 5, 6}
numbers.remove(3)         # Removing an element from the set
print(numbers)            # Output: {1, 2, 4, 5, 6}

Operations on Collections

Python provides various built-in functions and operators for working with collections, such as concatenation, slicing, membership testing, and more.

fruits = ["apple", "banana", "cherry"]
vegetables = ["carrot", "spinach", "broccoli"]
combined = fruits + vegetables  # Concatenating lists
print(combined)                 # Output: ['apple', 'banana', 'cherry', 'carrot', 'spinach', 'broccoli']
sliced = combined[1:4]          # Slicing a list
print(sliced)                   # Output: ['banana', 'cherry', 'carrot']
if "apple" in fruits:           # Membership testing
print("Apple is in the list")
numbers = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in numbers]  # List comprehension
print(squared)                       # Output: [1, 4, 9, 16, 25]

In the next chapter, we'll explore Python strings, including string formatting, string methods, and regular expressions.