Disclaimer: This post has been translated to English using a machine translation model. Please, let me know if you find any mistakes.
📚 **This entry is part of the _Complete Python Guide_ series**, divided into three chapters that should be read in order:
> * 👉 **Part 1: Data types**
* Part 2: Operators, control flow, and functions
* Part 3: Classes, objects, and advanced topics
1. Summary
We are going to make a brief introduction to Python, explaining the data types we have, the operators, the use of functions and classes. In addition, we will see how to use iterable objects, how to use modules, etc.
2. Python Data Types
There are 7 types of data in Python
- Text type:
str - Numeric:
int,float,complex - Sequences:
list,tuple,range - Mapping:
dict5. Conjuntos:set,frozenset - Booleans:
bool - Binary:
bytes,bytearray,memoryview
We can obtain the data type using the type() function
InputPythontype(5.)Copied
float
Python is a dynamically typed language, that is, you can have a variable of one type and then assign it another type
InputPythona = 5type(a)Copied
int
InputPythona = 'MaximoFN'type(a)Copied
str
Python infers variable types for you, but if you want to type them yourself, you can do so
InputPythonb = int(5.1)type(b), bCopied
(int, 5)
Although b has been initialized as 5.1, that is, it should be of type float, by casting it to type int, we see that it is of type int and its value is also 5
2.1. Cadenas
strings are character strings; these can be defined with double quotes " or single quotes '
InputPythonstring = "MaximoFN"stringCopied
'MaximoFN'
InputPythonstring = 'MaximoFN'stringCopied
'MaximoFN'
To write a very long string and avoid having a line that takes up too much space, it can be split across multiple lines
InputPythonstring = """Este es un ejemplo decomo estoy introduciendo un stringen varias lineas"""stringCopied
'Este es un ejemplo de como estoy introduciendo un string en varias lineas'
InputPythonstring = '''Este es un ejemplo decomo estoy introduciendo un stringen varias lineas'''stringCopied
'Este es un ejemplo de como estoy introduciendo un string en varias lineas'
However, we see that in the middle it has inserted the line break character. If we use the print() function, we will see how it no longer appears
InputPythonprint(string)Copied
Este es un ejemplo decomo estoy introduciendo un stringen varias lineas
As we have said, strings are sequences of characters, so we can navigate and iterate through them
InputPythonfor i in range(10):# Se indica a la función print que cuando imprima no termine con un salto de# linea para escribir todo en la misma lineaprint(string[i], end='')Copied
Este es un
We can obtain the length of our string using the len() function
InputPythonlen(string)Copied
73
Check if there is any specific string within ours
InputPython'ejemplo' in stringCopied
True
Strings have certain useful attributes, such as putting everything in uppercase
InputPythonprint(string.upper())Copied
ESTE ES UN EJEMPLO DECOMO ESTOY INTRODUCIENDO UN STRINGEN VARIAS LINEAS
all in lowercase
InputPythonprint(string.lower())Copied
este es un ejemplo decomo estoy introduciendo un stringen varias lineas
Replace characters
InputPythonprint(string.replace('o', '@'))Copied
Este es un ejempl@ dec@m@ est@y intr@duciend@ un stringen varias lineas
Get all the words
InputPythonprint(string.split())Copied
['Este', 'es', 'un', 'ejemplo', 'de', 'como', 'estoy', 'introduciendo', 'un', 'string', 'en', 'varias', 'lineas']
You can see all the string methods in this link
Another useful thing that can be done with strings is concatenating them
InputPythonstring1 = 'Maximo'string2 = 'FN'string1 + string2Copied
'MaximoFN'
Earlier we explained that the character \n corresponded to a line break; this special character corresponds to a set of special characters called Escape Characters. Let's see others
If we declare a string with double quotes and want to add a double quote inside the string, we use the escape character \"
InputPythonprint("Este es el blog de "MaximoFN"")Copied
Este es el blog de "MaximoFN"
The same applies to the single quote, we add \'
InputPythonprint('Este es el blog de 'MaximoFN'')Copied
Este es el blog de 'MaximoFN'
Now we have the problem of whether we want to add the character \ since, as we have seen, it is an escape character, so we solve it by putting a double backslash \
InputPythonprint('Este es el blog de \\MaximoFN\\')Copied
Este es el blog de \MaximoFN\
We already saw the newline escape character \n before
InputPythonprint('Este es el blog de \nMaximoFN')Copied
Este es el blog deMaximoFN
If we want to write from the beginning of the line, we add \r
InputPythonprint('Esto no se imprimirá \rEste es el blog de MaximoFN')Copied
Este es el blog de MaximoFN
If we want to add a large space (indentation), we use \t
InputPythonprint('Este es el blog de \tMaximoFN')Copied
Este es el blog de MaximoFN
We can delete a character with \b
InputPythonprint('Este es el blog de \bMaximoFN')Copied
Este es el blog deMaximoFN
We can add the ASCII code in octal using \ooo
InputPythonprint('\115\141\170\151\155\157\106\116')Copied
MaximoFN
Or add the ASCII code in hexadecimal using \xhh
InputPythonprint('\x4d\x61\x78\x69\x6d\x6f\x46\x4e')Copied
MaximoFN
Lastly, we can convert another data type into a string
InputPythonn = 5print(type (n))string = str(n)print(type(string))Copied
<class 'int'><class 'str'>
2.2. Numbers
2.2.1. Integers
Integers of the integer type
InputPythonn = 5n, type(n)Copied
(5, int)
2.2.2. Float
Floating-point numbers
InputPythonn = 5.1n, type(n)Copied
(5.1, float)
2.2.3. Complex numbers
Complex numbers
InputPythonn = 3 + 5jn, type(n)Copied
((3+5j), complex)
2.2.4. Conversion
Can numbers be converted between types
InputPythonn = 5n = float(n)n, type(n)Copied
(5.0, float)
InputPythonn = 5.1n = complex(n)n, type(n)Copied
((5.1+0j), complex)
InputPythonn = 5.1n = int(n)n, type(n)Copied
(5, int)
A complex number cannot be converted to int or float type
2.3. Sequences
2.3.1. Lists
Lists store multiple items in a variable. They are declared using the symbols [], with the items separated by commas
InputPythonlista = ['item0', 'item1', 'item2', 'item3', 'item4', 'item5']listaCopied
['item0', 'item1', 'item2', 'item3', 'item4', 'item5']
We can obtain the length of a list using the len() function
InputPythonlen(lista)Copied
6
Lists can have items of different types
InputPythonlista = ['item0', 1, True, 5.3, "item4", 5, 6.6]listaCopied
['item0', 1, True, 5.3, 'item4', 5, 6.6]
In Python, counting starts from position 0, that is, if we want to get the first element of the list
InputPythonlista[0]Copied
'item0'
But one of the powerful things about Python is that if we want to access the last position, we can use negative indices
InputPythonlista[-1]Copied
6.6
If instead of the last position in the list, we want the second-to-last one
InputPythonlista[-2]Copied
5
If we only want a range of values, for example, from the second to the fifth item, we access it using [2:5]
InputPythonlista[2:5]Copied
[True, 5.3, 'item4']
If the first number of the range is omitted, it means we want from the first item in the list up to the indicated item; that is, if we want from the first item to the fifth, we use [:5]
InputPythonlista[:5]Copied
['item0', 1, True, 5.3, 'item4']
If the last number in the range is omitted, it means we want from the specified item to the last one. That is, if we want from the third item to the last, we use [3:]
InputPythonlista[3:]Copied
[5.3, 'item4', 5, 6.6]
We can also choose the range of items with negative numbers; that is, if we want from the third-to-last to the second-to-last, we use [-3:-1]. This is useful when dealing with lists whose length is unknown, but where we know we want a range of values from the end, because, for example, the list was created from measurements taken over time and we want to know the last averages.
InputPythonlista[-3:-1]Copied
['item4', 5]
Can you check if an item is in the list
InputPython'item4' in listaCopied
True
2.3.1.1. Edit lists
Python lists are dynamic, that is, they can be modified. For example, the third item can be modified
InputPythonlista[2] = FalselistaCopied
['item0', 1, False, 5.3, 'item4', 5, 6.6]
It is also possible to modify a range of values
InputPythonlista[1:4] = [1.1, True, 3]listaCopied
['item0', 1.1, True, 3, 'item4', 5, 6.6]
Values can be added to the end of the list using the append() method
InputPythonlista.append('item7')listaCopied
['item0', 1.1, True, 3, 'item4', 5, 6.6, 'item7']
Or we can insert a value at a specific position using the insert() method
InputPythonlista.insert(2, 'insert')listaCopied
['item0', 1.1, 'insert', True, 3, 'item4', 5, 6.6, 'item7']
Can lists be combined using the extend() method
InputPythonlista2 = ['item8', 'item9']lista.extend(lista2)listaCopied
['item0', 1.1, 'insert', True, 3, 'item4', 5, 6.6, 'item7', 'item8', 'item9']
It is not necessary to extend the list using another list; it can be done using another type of Python iterable data (tuples, sets, dictionaries, etc.)
InputPythontupla = ('item10', 'item11')lista.extend(tupla)listaCopied
['item0',1.1,'insert',True,3,'item4',5,6.6,'item7','item8','item9','item10','item11']
We can remove a specific position using the pop() method
InputPythonlista.pop(2)listaCopied
['item0',1.1,True,3,'item4',5,6.6,'item7','item8','item9','item10','item11']
If the index is not specified, the last item is removed
InputPythonlista.pop()listaCopied
['item0', 1.1, True, 3, 'item4', 5, 6.6, 'item7', 'item8', 'item9', 'item10']
Or an item can be deleted by knowing its value using the remove() method
InputPythonlista.remove('item7')listaCopied
['item0', 1.1, True, 3, 'item4', 5, 6.6, 'item8', 'item9', 'item10']
With the del() function, you can also remove an item from the specified position
InputPythondel lista[3]listaCopied
['item0', 1.1, True, 'item4', 5, 6.6, 'item8', 'item9', 'item10']
If no index is specified, the entire list is deleted
With the clear() method, I leave the list empty
InputPythonlista.clear()listaCopied
[]
Can the number of items with a given value be obtained using the count() method?
InputPythonlista = [5, 4, 6, 5, 7, 8, 5, 3, 1, 5]lista.count(5)Copied
4
You can also obtain the first index of an item with a given value using the index() method.
InputPythonlista = [5, 4, 6, 5, 7, 8, 5, 3, 1, 5]lista.index(5)Copied
0
2.3.1.2. Comprensión de listas
We can operate through the list
InputPythonfruits = ["apple", "banana", "cherry", "kiwi", "mango"]newlist = []# Iteramos por todos los items de la listafor x in fruits:# Si el item contiene el caracter "a" lo añadimos a newlistif "a" in x:newlist.append(x)newlistCopied
['apple', 'banana', 'mango']
Another powerful feature of Python is list comprehensions, which allow you to do everything in a single line and make the code more compact
InputPythonfruits = ["apple", "banana", "cherry", "kiwi", "mango"]newlist = [x for x in fruits if "a" in x]newlistCopied
['apple', 'banana', 'mango']
The syntax is as follows:
newlist = [expression for item in iterable if condition == True]It can be used to perform operations on the original list
InputPythonnewlist = [x.upper() for x in fruits if "a" in x]newlistCopied
['APPLE', 'BANANA', 'MANGO']
2.3.1.3. Sort lists
To sort lists, we use the sort() method
InputPythonlista = [5, 8, 3, 4, 9, 5, 6]lista.sort()listaCopied
[3, 4, 5, 5, 6, 8, 9]
It also sorts them alphabetically
InputPythonlista = ["orange", "mango", "kiwi", "pineapple", "banana"]lista.sort()listaCopied
['banana', 'kiwi', 'mango', 'orange', 'pineapple']
When sorting alphabetically, distinguish between uppercase and lowercase letters
InputPythonlista = ["orange", "mango", "kiwi", "Pineapple", "banana"]lista.sort()listaCopied
['Pineapple', 'banana', 'kiwi', 'mango', 'orange']
They can be sorted in descending order using the reverse = True attribute
InputPythonlista = [5, 8, 3, 4, 9, 5, 6]lista.sort(reverse = True)listaCopied
[9, 8, 6, 5, 5, 4, 3]
They can be sorted in any way we want using the key attribute
InputPythondef myfunc(n):# devuelve el valor absoluto de n - 50return abs(n - 50)lista = [100, 50, 65, 82, 23]lista.sort(key = myfunc)listaCopied
[50, 65, 23, 82, 100]
Can this be used so that, for example, when sorting, it does not distinguish between uppercase and lowercase letters?
InputPythonlista = ["orange", "mango", "kiwi", "Pineapple", "banana"]lista.sort(key = str.lower)listaCopied
['banana', 'kiwi', 'mango', 'orange', 'Pineapple']
You can reverse the list using the reverse method
InputPythonlista = [5, 8, 3, 4, 9, 5, 6]lista.reverse()listaCopied
[6, 5, 9, 4, 3, 8, 5]
2.3.1.4. Copying lists
Lists cannot be copied using lista1 = lista2, since if lista1 is modified, lista2 is also modified
InputPythonlista1 = [5, 8, 3, 4, 9, 5, 6]lista2 = lista1lista1[0] = Truelista2Copied
[True, 8, 3, 4, 9, 5, 6]
So, the copy() method should be used.
InputPythonlista1 = [5, 8, 3, 4, 9, 5, 6]lista2 = lista1.copy()lista1[0] = Truelista2Copied
[5, 8, 3, 4, 9, 5, 6]
Or you have to use the list() constructor
InputPythonlista1 = [5, 8, 3, 4, 9, 5, 6]lista2 = list(lista1)lista1[0] = Truelista2Copied
[5, 8, 3, 4, 9, 5, 6]
2.3.1.5. Concatenate lists
Can lists be concatenated using the + operator
InputPythonlista1 = [5, 8, 3, 4, 9, 5, 6]lista2 = ['a', 'b', 'c']lista = lista1 + lista2listaCopied
[5, 8, 3, 4, 9, 5, 6, 'a', 'b', 'c']
Or by using the extend method
InputPythonlista1 = [5, 8, 3, 4, 9, 5, 6]lista2 = ['a', 'b', 'c']lista1.extend(lista2)lista1Copied
[5, 8, 3, 4, 9, 5, 6, 'a', 'b', 'c']
Another way to concatenate is to repeat the tuple X times using the * operator
InputPythonlista1 = ['a', 'b', 'c']lista2 = lista1 * 3lista2Copied
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
2.3.2. Tuples
Tuples are similar to lists: they store multiple items in a variable, can contain items of different types, but cannot be modified or reordered. They are defined using (), with the items separated by commas
Since they cannot be modified, tuples execute a little faster than lists, so if you do not need to modify the data, it is better to use tuples instead of lists
InputPythontupla = ('item0', 1, True, 3.3, 'item4', True)tuplaCopied
('item0', 1, True, 3.3, 'item4', True)
Its length can be obtained using the len() function
InputPythonlen (tupla)Copied
6
To create tuples with a single element, it is necessary to add a comma
InputPythontupla = ('item0',)tupla, type(tupla)Copied
(('item0',), tuple)
To access an element of the tuple, you do the same as with lists
InputPythontupla = ('item0', 1, True, 3.3, 'item4', True)print(tupla[0])print(tupla[-1])print(tupla[2:4])print(tupla[-4:-2])Copied
item0True(True, 3.3)(True, 3.3)
Can we check if there is an item in the tuple
InputPython'item4' in tuplaCopied
True
2.3.2.1. Modify tuples
Although tuples are not modifiable, they can be modified by converting them to lists, modifying the list, and then converting it back to a tuple
InputPythonlista = list(tupla)lista[4] = 'ITEM4'tupla = tuple(lista)tuplaCopied
('item0', 1, True, 3.3, 'ITEM4', True)
By converting it into a list, we can make all the modifications seen in lists
What you can do is delete the entire tuple
InputPythondel tuplaif 'tupla' not in locals():print("tupla eliminada")Copied
tupla eliminada
2.3.2.2. Unpacking tuples
When we create tuples, we are actually packaging data
InputPythontupla = ('item0', 1, True, 3.3, 'item4', True)tuplaCopied
('item0', 1, True, 3.3, 'item4', True)
but we can unpack them
InputPythonitem0, item1, item2, item3, item4, item5 = tuplaitem0, item1, item2, item3, item4, item5Copied
('item0', 1, True, 3.3, 'item4', True)
If we want to extract fewer data than the length of the tuple, we add a *
InputPythonitem0, item1, item2, *item3 = tuplaitem0, item1, item2, item3Copied
('item0', 1, True, [3.3, 'item4', True])
Can the asterisk * be placed somewhere else if, for example, what we want is the last item?
InputPythonitem0, item1, *item2, item5 = tuplaitem0, item1, item2, item5Copied
('item0', 1, [True, 3.3, 'item4'], True)
2.3.2.3. Concatenate tuples
Tuples can be concatenated using the + operator
InputPythontupla1 = ("a", "b" , "c")tupla2 = (1, 2, 3)tupla3 = tupla1 + tupla2tupla3Copied
('a', 'b', 'c', 1, 2, 3)
Another way to concatenate is to repeat the tuple X times using the * operator
InputPythontupla1 = ("a", "b" , "c")tupla2 = tupla1 * 3tupla2Copied
('a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c')
2.3.2.4. Tuple methods
Tuples have two methods, the first is the count() method, which returns the number of times an item appears within the tuple
InputPythontupla = (5, 4, 6, 5, 7, 8, 5, 3, 1, 5)tupla.count(5)Copied
4
Another method is index() which returns the first position of an item within the tuple
InputPythontupla = (5, 4, 6, 5, 7, 8, 5, 3, 1, 5)tupla.index(5)Copied
0
2.3.3. Range
With range() we can create a sequence of numbers, starting from 0 (by default), incrementing by 1 (by default), and stopping before a specified number
range(start, stop, step)For example, if we want a sequence from 0 to 5 (excluding 5)
InputPythonfor i in range(5):print(f'{i} ', end='')Copied
0 1 2 3 4
Yes, for example, if we don't want it to start at 0
InputPythonfor i in range(2, 5):print(f'{i} ', end='')Copied
2 3 4
InputPythonfor i in range(-2, 5):print(f'{i} ', end='')Copied
-2 -1 0 1 2 3 4
Finally, if we do not want it to increase by 1, if for example we want a sequence of even numbers.
InputPythonfor i in range(0, 10, 2):print(f'{i} ', end='')Copied
0 2 4 6 8
2.4. Dictionaries
Dictionaries are used to store data in key:value pairs. They are mutable, unordered, and do not allow duplicates. They are defined using the {} symbols. They support items of different data types.
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964,"colors": ["red", "white", "blue"]}diccionarioCopied
{'brand': 'Ford','model': 'Mustang','year': 1964,'colors': ['red', 'white', 'blue']}
As stated, they do not allow duplicates
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964,"year": 2000,"colors": ["red", "white", "blue"]}diccionario["year"]Copied
2000
Its length can be obtained using the len() function.
InputPythonlen(diccionario)Copied
4
As can be seen, the length is 4 and not 5, since year is counted only once
2.4.1. Accessing items
To access an element, we can do it through its key
InputPythondiccionario["model"]Copied
'Mustang'
It can also be accessed using the get method
InputPythondiccionario.get("model")Copied
'Mustang'
To know all the keys of the dictionaries, you can use the keys() method
InputPythondiccionario.keys()Copied
dict_keys(['brand', 'model', 'year', 'colors'])
A variable can be used to point to the dictionary keys, so by calling it once it is necessary
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se declara una vez la variable que apunta a las keysx = diccionario.keys()print(x)# Se añade una nueva keydiccionario["color"] = "white"# Se consulta la variable que apunta a las keyprint(x)Copied
dict_keys(['brand', 'model', 'year'])dict_keys(['brand', 'model', 'year', 'color'])
To obtain the values from the dictionary, you can use the values() method.
InputPythondiccionario.values()Copied
dict_values(['Ford', 'Mustang', 1964, 'white'])
A variable can be used to point to the dictionary's values, so by calling it once it is necessary
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se declara una vez la variable que apunta a los valuesx = diccionario.values()print(x)# Se modifica un valuediccionario["year"] = 2020# Se consulta la variable que apunta a los valuesprint(x)Copied
dict_values(['Ford', 'Mustang', 1964])dict_values(['Ford', 'Mustang', 2020])
If what you want are the complete items, that is, keys and values, you need to use the items() method
InputPythondiccionario.items()Copied
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2020)])
A variable can be used to point to the dictionary's items, so by calling it once it is necessary
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se declara una vez la variable que apunta a los itemsx = diccionario.items()print(x)# Se modifica un valuediccionario["year"] = 2020# Se consulta la variable que apunta a los itemsprint(x)Copied
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2020)])
Can you check if a key exists in the dictionary
InputPython"model" in diccionarioCopied
True
2.4.2. Modify the items
Can an item be modified by accessing it directly
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se modifica un itemdiccionario["year"] = 2020diccionarioCopied
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Or it can be modified using the update() method
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se modifica un itemdiccionario.update({"year": 2020})diccionarioCopied
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
2.4.3. Add items
You can add an item by adding it in this way:
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se modifica un itemdiccionario["colour"] = "blue"diccionarioCopied
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'colour': 'blue'}
Or it can be added using the update() method
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se modifica un itemdiccionario.update({"colour": "blue"})diccionarioCopied
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'colour': 'blue'}
2.4.4. Remove items
Can an item with a specific key be removed using the pop() method?
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se elimina un itemdiccionario.pop("model")diccionarioCopied
{'brand': 'Ford', 'year': 1964}
Or you can delete an item with a specific key using del, specifying the key name between the [] symbols
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se elimina un itemdel diccionario["model"]diccionarioCopied
{'brand': 'Ford', 'year': 1964}
The entire dictionary is deleted if del is used and the key of an item is not specified
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se elimina un itemdel diccionarioif 'diccionario' not in locals():print("diccionario eliminado")Copied
diccionario eliminado
If what you want is to delete the last item entered, you can use the popitem() method
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se elimina el último item introducidodiccionario.popitem()diccionarioCopied
{'brand': 'Ford', 'model': 'Mustang'}
If you want to clear the dictionary, you should use the clear() method
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964}diccionario.clear()diccionarioCopied
{}
2.4.5. Copying dictionaries
Dictionaries cannot be copied with diccionario1 = diccionario2, since if diccionario1 is modified, diccionario2 is also modified
InputPythondiccionario1 = {"brand": "Ford","model": "Mustang","year": 1964}diccionario2 = diccionario1diccionario1["year"] = 2000diccionario2["year"]Copied
2000
So the copy() method has to be used
InputPythondiccionario1 = {"brand": "Ford","model": "Mustang","year": 1964}diccionario2 = diccionario1.copy()diccionario1["year"] = 2000diccionario2["year"]Copied
1964
Or you have to use the dict() dictionary constructor
InputPythondiccionario1 = {"brand": "Ford","model": "Mustang","year": 1964}diccionario2 = dict(diccionario1)diccionario1["year"] = 2000diccionario2["year"]Copied
1964
2.4.6. Nested dictionaries
Dictionaries can have items of any data type, even other dictionaries. This type of dictionary is called nested dictionaries.
InputPythondiccionario_nested = {"child1" : {"name" : "Emil","year" : 2004},"child2" : {"name" : "Tobias","year" : 2007},"child3" : {"name" : "Linus","year" : 2011}}diccionario_nestedCopied
{'child1': {'name': 'Emil', 'year': 2004},'child2': {'name': 'Tobias', 'year': 2007},'child3': {'name': 'Linus', 'year': 2011}}
InputPythonchild1 = {"name" : "Emil","year" : 2004}child2 = {"name" : "Tobias","year" : 2007}child3 = {"name" : "Linus","year" : 2011}diccionario_nested = {"child1" : child1,"child2" : child2,"child3" : child3}diccionario_nestedCopied
{'child1': {'name': 'Emil', 'year': 2004},'child2': {'name': 'Tobias', 'year': 2007},'child3': {'name': 'Linus', 'year': 2011}}
2.4.7. Dictionary methods
These are the methods that can be used in dictionaries
2.4.8. Comprensión de diccionarios
Just as we could do list comprehensions using the syntax
list_comprehension = [expression for item in iterable if condition == True]We can make dictionaries comprehensions using the following syntax
dictionary_comprehension = {key_expression: value_expression for item in iterable if condition == True}Let's see an example
InputPythondictionary_comprehension = {x: x**2 for x in (2, 4, 6) if x > 2}dictionary_comprehensionCopied
{4: 16, 6: 36}
2.5. Sets
2.5.1. Set
sets are used in Python to store a collection of items in a single variable. Items of different types can be stored. They are unordered and have no index.
They differ from lists in that they have neither order nor index.
They are declared using the symbols {}
Since set is a reserved word in Python, we create a set named set_
InputPythonset_ = {'item0', 1, 5.3, "item4", 5, 6.6}set_Copied
{1, 5, 5.3, 6.6, 'item0', 'item4'}
There cannot be duplicate items; if any duplicate item is found, only one is kept
InputPythonset_ = {'item0', 1, 5.3, "item4", 5, 6.6, 'item0'}set_Copied
{1, 5, 5.3, 6.6, 'item0', 'item4'}
Can you get the length of the set using the len() function?
InputPythonlen(set_)Copied
6
As can be seen, the length of the set is 6 and not 7, since it is left with only one 'item0'
Can you check if an item is in the set
InputPython'item4' in set_Copied
True
2.5.1.1. Add items
Can an element be added to the set using the add() method?
InputPythonset_.add(8.8)set_Copied
{1, 5, 5.3, 6.6, 8.8, 'item0', 'item4'}
Can another set be added through the update() method?
InputPythonset2 = {"item5", "item6", 7}set_.update(set2)set_Copied
{1, 5, 5.3, 6.6, 7, 8.8, 'item0', 'item4', 'item5', 'item6'}
Items from Python iterable data types can also be added
InputPythonlista = ["item9", 10, 11.2]set_.update(lista)set_Copied
{1, 10, 11.2, 5, 5.3, 6.6, 7, 8.8, 'item0', 'item4', 'item5', 'item6', 'item9'}
2.5.1.2. Remove items
A specific item can be removed using the remove() method
InputPythonset_.remove('item9')set_Copied
{1, 10, 11.2, 5, 5.3, 6.6, 7, 8.8, 'item0', 'item4', 'item5', 'item6'}
Or by using the discard() method
InputPythonset_.discard('item6')set_Copied
{1, 10, 11.2, 5, 5.3, 6.6, 7, 8.8, 'item0', 'item4', 'item5'}
Using the pop() method, you can remove the last item, but since sets are unordered there is no way to know which the last item is. The pop() method returns the removed item
InputPythonprint(f"set antes de pop(): {set_}")eliminado = set_.pop()print(f"Se ha eliminado {eliminado}")Copied
set antes de pop(): {1, 5, 5.3, 6.6, 8.8, 7, 10, 11.2, 'item5', 'item0', 'item4'}Se ha eliminado 1
Using the clear() method, the set can be emptied
InputPythonset_.clear()set_Copied
set()
Finally, with del you can remove the set
InputPythondel set_if 'set_' not in locals():print("set eliminado")Copied
set eliminado
2.5.1.3. Merge items
One way to join sets is by using the union() method
InputPythonset1 = {"a", "b" , "c"}set2 = {1, 2, 3}set3 = set1.union(set2)set3Copied
{1, 2, 3, 'a', 'b', 'c'}
Another way is by using the update() method, but in this way a set is added to another one; a new one is not created
InputPythonset1 = {"a", "b" , "c"}set2 = {1, 2, 3}set1.update(set2)set1Copied
{1, 2, 3, 'a', 'b', 'c'}
These join methods eliminate duplicates, but if we want to obtain the duplicate elements in two sets, we use the intersection() method.
InputPythonset1 = {"apple", "banana", "cherry"}set2 = {"google", "microsoft", "apple"}set3 = set1.intersection(set2)set3Copied
{'apple'}
If we want to obtain the duplicate elements in two sets, but without creating a new set, we use the intersection_update() method
InputPythonset1 = {"apple", "banana", "cherry"}set2 = {"google", "microsoft", "apple"}set1.intersection_update(set2)set1Copied
{'apple'}
Now, conversely, if we want to keep the non-duplicates, we use the symmetric_difference() method.
The difference between this and the union of two sets is that in the union it keeps all the items, but the duplicated ones are only taken once. Now we keep the ones that are not duplicated.
InputPythonset1 = {"apple", "banana", "cherry"}set2 = {"google", "microsoft", "apple"}set3 = set1.symmetric_difference(set2)set3Copied
{'banana', 'cherry', 'google', 'microsoft'}
If we want to keep the non-duplicates without creating a new set, we use the symmetric_difference_update() method
InputPythonset1 = {"apple", "banana", "cherry"}set2 = {"google", "microsoft", "apple"}set1.symmetric_difference_update(set2)set1Copied
{'banana', 'cherry', 'google', 'microsoft'}
2.5.1.4. Set methods
These are the methods that can be used in sets
2.5.2. FrozenSet
frozensets are like sets, but with the caveat that they are immutable, just as tuples are like lists but immutable. Therefore, we will not be able to add or remove items
2.6. Booleans
There are only two booleans in Python: True and False
Using the bool() function, you can evaluate whether anything is True or False
InputPythonprint(bool("Hello"))print(bool(15))print(bool(0))Copied
TrueTrueFalse
2.6.1. Other data types True and False
The following data are True:
- Any non-empty string
- Any number except 0* Any non-empty list, tuple, dictionary, or set
InputPythonprint(bool("Hola"))print(bool(""))Copied
TrueFalse
InputPythonprint(bool(3))print(bool(0))Copied
TrueFalse
InputPythonlista = [1, 2, 3]print(bool(lista))lista = []print(bool(lista))Copied
TrueFalse
InputPythontupla = (1, 2, 3)print(bool(tupla))tupla = ()print(bool(tupla))Copied
TrueFalse
InputPythondiccionario = {"brand": "Ford","model": "Mustang","year": 1964,"colors": ["red", "white", "blue"]}print(bool(diccionario))diccionario.clear()print(bool(diccionario))Copied
TrueFalse
InputPythonset_ = {'item0', 1, 5.3, "item4", 5, 6.6}print(bool(set_))set_.clear()print(bool(set_))Copied
TrueFalse
2.7. Binaries
2.7.1. Bytes
The bytes type is an immutable sequence of bytes. They only support ASCII characters. Bytes can also be represented by integers whose values must satisfy 0 <= x < 256
To create a byte type, we must first enter the character b
InputPythonbyte = b"MaximoFN"byteCopied
b'MaximoFN'
They can also be created using their bytes() constructor
InputPythonbyte = bytes(10)byteCopied
b'