Collections in Python
In Python, a collection is a group of objects that can be stored and manipulated together. Python has several built-in collection types that are very useful for working with collections of data. These types include lists, tuples, sets, and dictionaries. In this article, we’ll explore the various collection types in Python and how to use them effectively.
Lists
A list is a collection of elements that are ordered and mutable. Lists are declared using square brackets and elements are separated by commas.
fruits = ["apple", "banana", "cherry"]
print(fruits)
Output:
['apple', 'banana', 'cherry']
Basic operations
Accessing elements
Elements in a list can be accessed using index numbers. Indexes in Python start from 0. To access the first element of a list, you would use the index number 0. Here’s an example:
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
Output:
apple
Modifying elements
Elements in a list can be modified by assigning a new value to the specific index number. Here’s an example:
fruits = ["apple", "banana", "cherry"]
fruits[1] = "kiwi"
print(fruits)
Output:
['apple', 'kiwi', 'cherry']
Adding elements
You can add elements to the end of a list using the append() method. Here’s an example:
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)
Output:
['apple', 'banana', 'cherry', 'orange']
Removing elements
You can remove elements from a list using the remove() method. Here’s an example:
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)
Output:
['apple', 'cherry']
Multi-dimensional lists
You can also create multi-dimensional lists, which are lists of lists. Here’s an example of a 2-dimensional list:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][2]) # prints 6
Tuples
A tuple is similar to a list, but it is immutable, which means that you cannot modify the elements once they are created. Tuples are declared using parentheses and elements are separated by commas.
fruits = ("apple", "banana", "cherry")
print(fruits)
Output:
('apple', 'banana', 'cherry')
Basic operations
Accessing elements
Elements in a tuple can be accessed using index numbers, just like in a list. Here’s an example:
fruits = ("apple", "banana", "cherry")
print(fruits[0])
Output:
apple
Because tuples are immutable, you cannot modify the elements of a tuple.
Packing and unpacking
You can pack multiple elements into a tuple by separating them with commas. Here’s an example:
fruits = "apple", "banana", "cherry"
print(fruits)
Output:
('apple', 'banana', 'cherry')
You can also unpack a tuple into multiple variables, like this:
fruits = ("apple", "banana", "cherry")
a, b, c = fruits
print(a) # prints "apple"
print(b) # prints "banana"
print(c) # prints "cherry"
Sets
A set is an unordered collection of unique elements. Sets are declared using curly braces or the set() function.
fruits = {"apple", "banana", "cherry"}
print(fruits)
Output:
{'cherry', 'banana', 'apple'}
Basic operations
Adding elements
You can add elements to a set using the add() method. Here’s an example:
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits)
Output:
{'cherry', 'banana', 'orange', 'apple'}
Removing elements
You can remove elements from a set using the remove() method. Here’s an example:
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)
Output:
{'cherry', 'apple'}
Set operations
Sets support a variety of set operations, such as union, intersection, and difference. Here are some examples:
fruits = {"apple", "banana", "cherry"}
colors = {"red", "green", "blue"}
# Union
print(fruits.union(colors)) # prints {'banana', 'red', 'cherry', 'green', 'apple', 'blue'}
# Intersection
print(fruits.intersection(colors)) # prints set()
# Difference
print(fruits.difference(colors)) # prints {'banana', 'cherry', 'apple'}
Dictionaries
A dictionary is a collection of key-value pairs. Dictionaries are declared using curly braces and colons are used to separate keys and values.
person = {"name": "John", "age": 30, "city": "New York"}
print(person)
Output:
{'name': 'John', 'age': 30, 'city': 'New York'}
Basic operations
Accessing elements
You can access the value of a specific key in a dictionary using square brackets and the key name. Here’s an example:
person = {"name": "John", "age": 30, "city": "New York"}
print(person["name"]) # prints "John"
Modifying elements
You can modify the value of a specific key in a dictionary by assigning a new value to that key. Here’s an example:
person = {"name": "John", "age": 30, "city": "New York"}
person["age"] = 40
print(person) # prints {'name': 'John', 'age': 40, 'city': 'New York'}
Adding elements
You can add a new key-value pair to a dictionary by assigning a value to a new key. Here’s an example:
person = {"name": "John", "age": 30, "city": "New York"}
person["country"] = "USA"
print(person) # prints {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
Removing elements
You can remove a key-value pair from a dictionary using the del keyword. Here’s an example:
person = {"name": "John", "age": 30, "city": "New York"}
del person["age"]
print(person) # prints {'name': 'John', 'city': 'New York'}
Conclusion
In this article, we’ve covered the various collection types in Python, including lists, tuples, sets, and dictionaries. We’ve also covered basic operations for each type and shown how to use them effectively. By understanding how to use collections in Python, you’ll be able to write more efficient and expressive code.