Collections
Tuples (tuple)​
Represent ordered and immutable collections of elements. They use () between their values. Once a tuple is created, it's not possible to change it—you can't modify values or add new ones.
Tuples are the simplest composite type of all and quite common to be used in Python. Just like we previously saw that the string "ABC" is a sequence of characters, with tuples we can create a sequence of values that can be of any type.
In Python, whenever one or more objects are chained with , this will be interpreted as a tuple type object.
The most interesting characteristic of tuples is called unpacking or decomposition. Unpacking allows you to do the reverse operation of assignment.
# Assignment, could be without parentheses
>>> person = ("David", 37, "Vila Velha", "[email protected]")
# Unpacking
>>> name, age, city, email = person
>>> print("Name:", name)
Name: David
>>> print("Age:", age)
Age: 37
>>> print("City:", city)
City: Vila Velha
>>> print("Email:", email)
Email: david@example.com
>>> person[0]
'David'
>>> person[1]
37
>>>
Lists (list)​
Represent ordered and mutable collections of elements. They use [] between their values. Lists are quite similar to tuples and most operations we can do with tuples we can also do with lists. The difference is that we can add, remove, and reorder elements, i.e., they're mutable.
>>> fruits = ["apple", "banana", "orange", "strawberry"]
>>> print(fruits)
['apple', 'banana', 'orange', 'strawberry']
>>> type(fruits)
<class 'list'>
>>> print(fruits[0])
apple
>>> print(fruits[1])
banana
# Add blackberry to the end
>>> fruits.append("blackberry")
# Insert pineapple at position 0
>>> fruits.insert(0, "pineapple")
# Insert avocado at position 3
>>> fruits.insert(3, "avocado")
>>> print(fruits)
['pineapple', 'apple', 'banana', 'avocado', 'orange', 'strawberry', 'blackberry']
>>>
# Adding lists
>>> fruits2 = ["passion fruit","grape"]
>>> new_fruits = fruits + fruits2
>>> print(new_fruits)
['pineapple', 'apple', 'banana', 'avocado', 'orange', 'strawberry', 'blackberry', 'passion fruit', 'grape']
# Removing banana from the new list
>>> new_fruits.remove("banana")
>>> print(new_fruits)
['pineapple', 'apple', 'avocado', 'orange', 'strawberry', 'blackberry', 'passion fruit', 'grape']
# Removing the last element
>>> new_fruits.pop()
'grape'
>>> print(new_fruits)
['pineapple', 'apple', 'avocado', 'orange', 'strawberry', 'blackberry', 'passion fruit']
>>>
Sets (set)​
Represent unordered and non-duplicated collections of elements. By default, they don't have a specific order, which means there's no guarantee which element will be considered the "first" element. Thus, sets are usually transformed into some ordered list for printing. There's a set called frozenset (fset) that doesn't allow adding and removing.
>>> colors
{'blue', 'red', 'green'}
>>> colors = {"red", "green", "blue"}
>>> colors
{'blue', 'red', 'green'}
>>> type(colors)
<class 'set'>
>>># I'll force the entry of two reds which shouldn't be repeated.
>>> colors = {"red", "green", "blue", "red"}
>>> type(colors)
<class 'set'>
>>> colors
{'blue', 'red', 'green'} # Even so it eliminated the extra red.
>>># Adding and removing colors
>>> colors.add("yellow")
>>> colors.remove("green")
>>> print("blue" in colors)
>>># Notice the print function here checks if we have the keys and doesn't show their value.
True
>>> print("black" in colors) # Output: False
False
>>> print(colors)
{'blue', 'red', 'yellow'}
>>># We need other resources to print a set, which will be seen later. Don't worry about this now.
>>> for color in colors:
... print(color)
...
blue
red
yellow
Dictionaries (dict)​
Represent collections of key-value pairs, where each value is accessed through its key. Dictionaries are a mix between set and list.
>>> person = {
... "name": "David",
... "age": 36,
... "city": "Vila Velha",
... "email": "[email protected]"
... }
>>> print("Name:", person["name"])
Name: David
>>> print("Age:", person["age"])
Age: 36
>>> print("City:", person["city"])
City: Vila Velha
>>> print("Email:", person["email"])
Email: david@example.com
>>># Adding a new key-value pair to the dictionary
>>> person["phone"] = "(11) 01234-5678"
>>># Modifying an existing value in the dictionary
>>> person["age"] = 37
>>># Removing a key-value pair from the dictionary
>>> del person["email"]
>>> print(person)
{'name': 'David', 'age': 37, 'city': 'Vila Velha', 'phone': '(11) 01234-5678'}
>>>
We can also have composite objects
product = {
"name": "Pen",
"colors": ["blue", "white"],
"price": 3.23,
"dimension" {
"height": 12.1,
"width": 0.8,
},
"in_stock: True,
"code": 45678,
"barcode": None,
}
# And to initialize empty
client = {}
# or
client = dict()
It's also possible to combine two dictionaries.
>>> client = {"name": "David", "city": "Vila Velha"}
>>> extra = {"cpf": "123456789-00"}
>>> final = {**client, **extra}
>>> print(final)
{'name': 'David', 'city': 'Vila Velha', 'cpf': '123456789-00'}
Or doing update in place.
client.update({"state": "es"})
>>> print(client)
{'name': 'David', 'city': 'Vila Velha', 'state': 'es'}
If a key doesn't exist in the dictionary, Python raises an error called KeyError
print(client["phone"])
...
KeyError 'phone'
To avoid the error, we can use the get method which searches for the key and if it doesn't exist
returns a default value which is initially None
print(client.get("phone"))
'None'
# Defining the default return to (00)99999-9999
print(client.get("phone", "(00)99999-9999"))
'(00)99999-9999'
Bytesarray (bytearray)​
Represent mutable sequences of bytes that store a byte sequence. It's similar to the bytes data type, but with the fundamental difference that a bytearray can be modified, while a bytes object is immutable. This makes this structure suitable for situations where you need to change data at the byte level efficiently.
>>> data = bytearray(b'RellO')
>>> data[0] = 72 # Modifying the first byte to 'H'
>>> data[4] = 111 # Modifying the last byte to 'o'
>>> data.append(33) # Adding the byte '!'
>>> print(data)
bytearray(b'Hello!')
>>> data.extend(b' World') # Adding a byte sequence
>>> print(data) # Output: bytearray(b'Hello World!')
bytearray(b'Hello! World')
>>> byte_list = list(data) # Converting a bytearray to a list of bytes
>>> print(byte_list)
[72, 101, 108, 108, 111, 33, 32, 87, 111, 114, 108, 100]
>>>