Disclaimer: This post has been translated to English using a machine translation model. Please, let me know if you find any mistakes.
1. Summary
Let's make a brief introduction to Python, explaining the data types we have, operators, the use of functions and classes. Additionally, we will see how to use iterable objects, how to use modules, etc.

2. Data types in Python
There are 7 data types in Python
- Text type:
str
- Numerical:
int
,float
,complex
- Sequences:
list
,tuple
,range
- Mapping:
dict
- Sets:
set
,frozenset
- Booleans:
bool
- Binaries:
bytes
,bytearray
,memoryview
We can get the data type using the type()
function.
type(5.)
float
Python is a dynamically typed language, which means you can have a variable of one type and then assign it another type.
a = 5type(a)
int
a = 'MaximoFN'type(a)
str
Python types variables for you, but if you want to type them yourself, you can do so.
b = int(5.1)type(b), b
(int, 5)
Although b
has been initialized as 5.1
, that is, it should be of type float
, when we type it as int
, we see that it is of type int
and its value is 5
2.1. Strings
strings
are sequences of characters, these can be defined with double quotes "
or single quotes '
string = "MaximoFN"string
'MaximoFN'
string = 'MaximoFN'string
'MaximoFN'
To write a very long string
and not have a line that takes up too much space, it can be introduced on multiple lines
string = """Este es un ejemplo decomo estoy introduciendo un stringen varias lineas"""string
'Este es un ejemplo de como estoy introduciendo un string en varias lineas'
string = '''Este es un ejemplo decomo estoy introduciendo un stringen varias lineas'''string
'Este es un ejemplo de como estoy introduciendo un string en varias lineas'
However, we see that in the middle it has inserted the character indicates a line break. If we use the print()
function, we will see that it no longer appears.
print(string)
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.
for 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='')
Este es un
We can get the length of our string using the len()
function.
len(string)
73
Check if there is a specific string within ours
'ejemplo' in string
True
Strings have certain useful attributes, such as converting everything to uppercase.
print(string.upper())
ESTE ES UN EJEMPLO DECOMO ESTOY INTRODUCIENDO UN STRINGEN VARIAS LINEAS
all in lowercase
print(string.lower())
este es un ejemplo decomo estoy introduciendo un stringen varias lineas
Replace characters
print(string.replace('o', '@'))
Este es un ejempl@ dec@m@ est@y intr@duciend@ un stringen varias lineas
Get all the words
print(string.split())
['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.
string1 = 'Maximo'string2 = 'FN'string1 + string2
'MaximoFN'
We previously explained that the character \n
corresponds to a line break. This special character is part of a series of special characters called Escape Characters
. Let's look at some others.
If we declare a string with double quotes and want to add a double quote inside the string, we use the escape character \"
print("Este es el blog de "MaximoFN"")
Este es el blog de "MaximoFN"
The same with the single quote, we add \'
print('Este es el blog de 'MaximoFN'')
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 \
.
print('Este es el blog de \\MaximoFN\\')
Este es el blog de \MaximoFN\
We have already seen the newline escape character \n
print('Este es el blog de \nMaximoFN')
Este es el blog deMaximoFN
If we want to write from the beginning of the line, we add \r
print('Esto no se imprimirá \rEste es el blog de MaximoFN')
Este es el blog de MaximoFN
If we want to add a large space (indent) we use \t
print('Este es el blog de \tMaximoFN')
Este es el blog de MaximoFN
We can delete a character with \b
print('Este es el blog de \bMaximoFN')
Este es el blog deMaximoFN
We can add the ASCII code in octal using \ooo
print('\115\141\170\151\155\157\106\116')
MaximoFN
Or add the ASCII code in hexadecimal using \xhh
print('\x4d\x61\x78\x69\x6d\x6f\x46\x4e')
MaximoFN
Lastly, we can convert another type of data into a string
n = 5print(type (n))string = str(n)print(type(string))
<class 'int'><class 'str'>
2.2. Numbers
2.2.1. Integers
Integer numbers
n = 5n, type(n)
(5, int)
2.2.2. Float
Floating-point numbers
n = 5.1n, type(n)
(5.1, float)
2.2.3. Complex
Complex numbers
n = 3 + 5jn, type(n)
((3+5j), complex)
2.2.4. Conversion
Numbers can be converted between types
n = 5n = float(n)n, type(n)
(5.0, float)
n = 5.1n = complex(n)n, type(n)
((5.1+0j), complex)
n = 5.1n = int(n)n, type(n)
(5, int)
A complex number cannot be converted to type int
or type float
2.3. Sequences
2.3.1. Lists
Lists store multiple items in a variable. They are declared using the []
symbols, with items separated by commas.
lista = ['item0', 'item1', 'item2', 'item3', 'item4', 'item5']lista
['item0', 'item1', 'item2', 'item3', 'item4', 'item5']
We can get the length of a list using the len()
function.
len(lista)
6
Lists can have items of different types
lista = ['item0', 1, True, 5.3, "item4", 5, 6.6]lista
['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
lista[0]
'item0'
But one of the powerful things about Python is that if we want to access the last position we can use negative indices
lista[-1]
6.6
If instead of the last position in the list we want the penultimate one
lista[-2]
5
If we only want a range of values, for example, from the second to the fifth item, we access them via [2:5]
lista[2:5]
[True, 5.3, 'item4']
If the first number in the range is omitted, it means we want from the first item in the list to the indicated item, that is, if we want from the first item to the fifth, we use [:5]
lista[:5]
['item0', 1, True, 5.3, 'item4']
If the last number in the range is omitted, it means we want from the indicated item to the last. That is, if we want from the third item to the last, we use [3:]
.
lista[3:]
[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 you have lists whose length is unknown, but you know you want a range of values from the end, for example, because the list was created with measurements that are being taken and you want to know the last averages.
lista[-3:-1]
['item4', 5]
It can be checked if an item is in the list
'item4' in lista
True
2.3.1.1. Editing lists
Lists in Python are dynamic, meaning they can be modified. For example, you can modify the third item.
lista[2] = Falselista
['item0', 1, False, 5.3, 'item4', 5, 6.6]
A range of values can also be modified.
lista[1:4] = [1.1, True, 3]lista
['item0', 1.1, True, 3, 'item4', 5, 6.6]
Values can be added to the end of the list using the append()
method.
lista.append('item7')lista
['item0', 1.1, True, 3, 'item4', 5, 6.6, 'item7']
Or we can insert a value at a specific position using the insert()
method.
lista.insert(2, 'insert')lista
['item0', 1.1, 'insert', True, 3, 'item4', 5, 6.6, 'item7']
Lists can be joined using the extend()
method.
lista2 = ['item8', 'item9']lista.extend(lista2)lista
['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 iterable data type in Python (tuples
, sets
, dictionaries
, etc).
tupla = ('item10', 'item11')lista.extend(tupla)lista
['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.
lista.pop(2)lista
['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.
lista.pop()lista
['item0', 1.1, True, 3, 'item4', 5, 6.6, 'item7', 'item8', 'item9', 'item10']
Or an item can be removed knowing its value using the remove()
method.
lista.remove('item7')lista
['item0', 1.1, True, 3, 'item4', 5, 6.6, 'item8', 'item9', 'item10']
With the del()
function, you can also delete an item from the specified position.
del lista[3]lista
['item0', 1.1, True, 'item4', 5, 6.6, 'item8', 'item9', 'item10']
If the index is not specified, the entire list is deleted.
With the clear()
method, I empty the list.
lista.clear()lista
[]
The number of items with a specific value can be obtained using the count()
method.
lista = [5, 4, 6, 5, 7, 8, 5, 3, 1, 5]lista.count(5)
4
You can also get the first index of an item with a specific value using the index()
method.
lista = [5, 4, 6, 5, 7, 8, 5, 3, 1, 5]lista.index(5)
0
2.3.1.2. List comprehension
We can operate through the list
fruits = ["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)newlist
['apple', 'banana', 'mango']
Some of the powerful features of Python are list comprehensions
, which allow you to do everything in one line and make the code more compact.
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]newlist = [x for x in fruits if "a" in x]newlist
['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
newlist = [x.upper() for x in fruits if "a" in x]newlist
['APPLE', 'BANANA', 'MANGO']
2.3.1.3. Sorting lists
To order lists we use the sort()
method.
lista = [5, 8, 3, 4, 9, 5, 6]lista.sort()lista
[3, 4, 5, 5, 6, 8, 9]
It also sorts them alphabetically
lista = ["orange", "mango", "kiwi", "pineapple", "banana"]lista.sort()lista
['banana', 'kiwi', 'mango', 'orange', 'pineapple']
When sorting alphabetically, distinguish between uppercase and lowercase.
lista = ["orange", "mango", "kiwi", "Pineapple", "banana"]lista.sort()lista
['Pineapple', 'banana', 'kiwi', 'mango', 'orange']
They can be sorted in descending order using the attribute reverse = True
lista = [5, 8, 3, 4, 9, 5, 6]lista.sort(reverse = True)lista
[9, 8, 6, 5, 5, 4, 3]
They can be ordered in the way we want using the key
attribute.
def myfunc(n):# devuelve el valor absoluto de n - 50return abs(n - 50)lista = [100, 50, 65, 82, 23]lista.sort(key = myfunc)lista
[50, 65, 23, 82, 100]
This can be used, for example, so that when sorting, it does not distinguish between uppercase and lowercase.
lista = ["orange", "mango", "kiwi", "Pineapple", "banana"]lista.sort(key = str.lower)lista
['banana', 'kiwi', 'mango', 'orange', 'Pineapple']
The list can be reversed using the reverse
method.
lista = [5, 8, 3, 4, 9, 5, 6]lista.reverse()lista
[6, 5, 9, 4, 3, 8, 5]
2.3.1.4. Copying lists
Lists cannot be copied using list1 = list2
, because if list1
is modified, list2
is also modified.
lista1 = [5, 8, 3, 4, 9, 5, 6]lista2 = lista1lista1[0] = Truelista2
[True, 8, 3, 4, 9, 5, 6]
So, you have to use the copy()
method.
lista1 = [5, 8, 3, 4, 9, 5, 6]lista2 = lista1.copy()lista1[0] = Truelista2
[5, 8, 3, 4, 9, 5, 6]
Or you have to use the list constructor list()
lista1 = [5, 8, 3, 4, 9, 5, 6]lista2 = list(lista1)lista1[0] = Truelista2
[5, 8, 3, 4, 9, 5, 6]
2.3.1.5. Concatenating lists
Lists can be concatenated using the +
operator.
lista1 = [5, 8, 3, 4, 9, 5, 6]lista2 = ['a', 'b', 'c']lista = lista1 + lista2lista
[5, 8, 3, 4, 9, 5, 6, 'a', 'b', 'c']
Or using the extend
method
lista1 = [5, 8, 3, 4, 9, 5, 6]lista2 = ['a', 'b', 'c']lista1.extend(lista2)lista1
[5, 8, 3, 4, 9, 5, 6, 'a', 'b', 'c']
Another way to concatenate is to repeat the tuple X times using the *
operator
lista1 = ['a', 'b', 'c']lista2 = lista1 * 3lista2
['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 they cannot be modified or reordered. They are defined using ()
, with items separated by commas.
Since they cannot be modified, tuples execute a bit faster than lists, so if you don't need to modify the data, it's better to use tuples instead of lists.
tupla = ('item0', 1, True, 3.3, 'item4', True)tupla
('item0', 1, True, 3.3, 'item4', True)
Its length can be obtained using the len()
function.
len (tupla)
6
To create tuples with a single element, it is necessary to add a comma
tupla = ('item0',)tupla, type(tupla)
(('item0',), tuple)
To access an element of the tuple, proceed in the same way as with lists.
tupla = ('item0', 1, True, 3.3, 'item4', True)print(tupla[0])print(tupla[-1])print(tupla[2:4])print(tupla[-4:-2])
item0True(True, 3.3)(True, 3.3)
We can check if there is an item in the tuple
'item4' in tupla
True
2.3.2.1. Modifying tuples
Although tuples are not mutable, they can be modified by converting them to lists, modifying the list, and then converting it back to a tuple.
lista = list(tupla)lista[4] = 'ITEM4'tupla = tuple(lista)tupla
('item0', 1, True, 3.3, 'ITEM4', True)
By converting it to a list, we can make all the modifications seen in lists.
What can be done is to delete the complete tuple
del tuplaif 'tupla' not in locals():print("tupla eliminada")
tupla eliminada
2.3.22. Unpack tuples
When we create tuples, we are actually packaging data
tupla = ('item0', 1, True, 3.3, 'item4', True)tupla
('item0', 1, True, 3.3, 'item4', True)
but we can unpack them
item0, item1, item2, item3, item4, item5 = tuplaitem0, item1, item2, item3, item4, item5
('item0', 1, True, 3.3, 'item4', True)
If we want to extract fewer elements than the length of the tuple, we add a *
item0, item1, item2, *item3 = tuplaitem0, item1, item2, item3
('item0', 1, True, [3.3, 'item4', True])
The asterisk *
can be placed elsewhere if, for example, what we want is the last item.
item0, item1, *item2, item5 = tuplaitem0, item1, item2, item5
('item0', 1, [True, 3.3, 'item4'], True)
2.3.23. Concatenating tuples
Tuples can be concatenated using the +
operator
tupla1 = ("a", "b" , "c")tupla2 = (1, 2, 3)tupla3 = tupla1 + tupla2tupla3
('a', 'b', 'c', 1, 2, 3)
Another way to concatenate is to repeat the tuple X times using the *
operator
tupla1 = ("a", "b" , "c")tupla2 = tupla1 * 3tupla2
('a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c')
2.3.24. Tuple Methods
Tuples have two methods, the first is the count()
method which returns the number of times an item appears within the tuple.
tupla = (5, 4, 6, 5, 7, 8, 5, 3, 1, 5)tupla.count(5)
4
Another method is index()
which returns the first position of an item within the tuple.
tupla = (5, 4, 6, 5, 7, 8, 5, 3, 1, 5)tupla.index(5)
0
2.3.3. Range
With range()
we can create a sequence of numbers, starting from 0 (by default), it increments by 1 (by default) and stops before a specified number.
range(start, stop, step)
For example, if we want a sequence from 0 to 5 (not including 5)
for i in range(5):print(f'{i} ', end='')
0 1 2 3 4
If for example we don't want it to start at 0
for i in range(2, 5):print(f'{i} ', end='')
2 3 4
for i in range(-2, 5):print(f'{i} ', end='')
-2 -1 0 1 2 3 4
Lastly, if we don't want it to increment by 1, for example, if we want a sequence of even numbers.
for i in range(0, 10, 2):print(f'{i} ', end='')
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.
diccionario = {"brand": "Ford","model": "Mustang","year": 1964,"colors": ["red", "white", "blue"]}diccionario
{'brand': 'Ford','model': 'Mustang','year': 1964,'colors': ['red', 'white', 'blue']}
As has been said, duplicates are not allowed.
diccionario = {"brand": "Ford","model": "Mustang","year": 1964,"year": 2000,"colors": ["red", "white", "blue"]}diccionario["year"]
2000
Its length can be obtained using the len()
function.
len(diccionario)
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 so through its key
diccionario["model"]
'Mustang'
It can also be accessed using the get
method.
diccionario.get("model")
'Mustang'
To know all the key
s of dictionaries, you can use the keys()
method.
diccionario.keys()
dict_keys(['brand', 'model', 'year', 'colors'])
A variable can be used to point to the key
s of the dictionary, so that calling it once is necessary
diccionario = {"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)
dict_keys(['brand', 'model', 'year'])dict_keys(['brand', 'model', 'year', 'color'])
To get the values from the dictionary, you can use the values()
method.
diccionario.values()
dict_values(['Ford', 'Mustang', 1964, 'white'])
A variable can be used to point to the values
of the dictionary, so that calling it once is necessary.
diccionario = {"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)
dict_values(['Ford', 'Mustang', 1964])dict_values(['Ford', 'Mustang', 2020])
If what you want are the entire item
s, that is, key
s and value
s, you should use the items()
method.
diccionario.items()
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2020)])
A variable can be used to point to the item
s in the dictionary, so that calling it once is necessary.
diccionario = {"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)
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2020)])
It can be checked if a key
exists in the dictionary
"model" in diccionario
True
2.4.2. Modify the items
An item
can be modified by accessing it directly.
diccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se modifica un itemdiccionario["year"] = 2020diccionario
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Or it can be modified using the update()
method.
diccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se modifica un itemdiccionario.update({"year": 2020})diccionario
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
2.4.3. Adding Items
An item
can be added in this way:
diccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se modifica un itemdiccionario["colour"] = "blue"diccionario
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'colour': 'blue'}
Or it can be added using the update()
method.
diccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se modifica un itemdiccionario.update({"colour": "blue"})diccionario
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'colour': 'blue'}
2.4.4. Remove items
An item
with a specific key
can be removed using the pop()
method.
diccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se elimina un itemdiccionario.pop("model")diccionario
{'brand': 'Ford', 'year': 1964}
Or you can delete an item
with a specific key
using del
by specifying the key
name between the []
symbols.
diccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se elimina un itemdel diccionario["model"]diccionario
{'brand': 'Ford', 'year': 1964}
The dictionary will raise an error if del
is used and the key
of an item
is not specified.
diccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se elimina un itemdel diccionarioif 'diccionario' not in locals():print("diccionario eliminado")
diccionario eliminado
If what is desired is to remove the last item
introduced, the popitem()
method can be used.
diccionario = {"brand": "Ford","model": "Mustang","year": 1964}# Se elimina el último item introducidodiccionario.popitem()diccionario
{'brand': 'Ford', 'model': 'Mustang'}
If you want to clear the dictionary, you can use the clear()
method.
diccionario = {"brand": "Ford","model": "Mustang","year": 1964}diccionario.clear()diccionario
{}
2.4.5. Copying dictionaries
Dictionaries cannot be copied using dictionary1 = dictionary2
, because if you modify dictionary1
, dictionary2
will also be modified.
diccionario1 = {"brand": "Ford","model": "Mustang","year": 1964}diccionario2 = diccionario1diccionario1["year"] = 2000diccionario2["year"]
2000
So, you have to use the copy()
method.
diccionario1 = {"brand": "Ford","model": "Mustang","year": 1964}diccionario2 = diccionario1.copy()diccionario1["year"] = 2000diccionario2["year"]
1964
Or you have to use the dictionary constructor dict()
diccionario1 = {"brand": "Ford","model": "Mustang","year": 1964}diccionario2 = dict(diccionario1)diccionario1["year"] = 2000diccionario2["year"]
1964
2.4.6. Anidated Dictionaries
Dictionaries can have items
of any data type, even other dictionaries. These types of dictionaries are called nested
dictionaries.
diccionario_nested = {"child1" : {"name" : "Emil","year" : 2004},"child2" : {"name" : "Tobias","year" : 2007},"child3" : {"name" : "Linus","year" : 2011}}diccionario_nested
{'child1': {'name': 'Emil', 'year': 2004},'child2': {'name': 'Tobias', 'year': 2007},'child3': {'name': 'Linus', 'year': 2011}}
child1 = {"name" : "Emil","year" : 2004}child2 = {"name" : "Tobias","year" : 2007}child3 = {"name" : "Linus","year" : 2011}diccionario_nested = {"child1" : child1,"child2" : child2,"child3" : child3}diccionario_nested
{'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 on dictionaries.
2.4.8. Dictionary comprehension
igual que podemos hacer list comprehensions
mediante la sintaxis
list comprehension = [expression for item in iterable if condition == True]
We can create dictionary comprehensions
using the following syntax
dictionary comprehension = {key_expression: value_expression for item in iterable if condition == True}
Let's start with an example
dictionary_comprehension = {x: x**2 for x in (2, 4, 6) if x > 2}dictionary_comprehension
{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. They can store items of different types. They are unordered and do not have an 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
with the name set_
set_ = {'item0', 1, 5.3, "item4", 5, 6.6}set_
{1, 5, 5.3, 6.6, 'item0', 'item4'}
Items cannot be duplicated, if a duplicate item is found, only one is kept.
set_ = {'item0', 1, 5.3, "item4", 5, 6.6, 'item0'}set_
{1, 5, 5.3, 6.6, 'item0', 'item4'}
The length of the set
can be obtained using the len()
function.
len(set_)
6
As can be seen, the length of the set is 6 and not 7, since it remains with only one 'item0'
It can be checked if an item is in the set
'item4' in set_
True
2.5.1.1. Add items
An element can be added to a set using the add()
method.
set_.add(8.8)set_
{1, 5, 5.3, 6.6, 8.8, 'item0', 'item4'}
Another set can be added using the update()
method.
set2 = {"item5", "item6", 7}set_.update(set2)set_
{1, 5, 5.3, 6.6, 7, 8.8, 'item0', 'item4', 'item5', 'item6'}
Items can also be added from iterable data types in Python.
lista = ["item9", 10, 11.2]set_.update(lista)set_
{1, 10, 11.2, 5, 5.3, 6.6, 7, 8.8, 'item0', 'item4', 'item5', 'item6', 'item9'}
2.5.1.2. Remove items
An item can be removed using the remove()
method.
set_.remove('item9')set_
{1, 10, 11.2, 5, 5.3, 6.6, 7, 8.8, 'item0', 'item4', 'item5', 'item6'}
Or using the discard()
method
set_.discard('item6')set_
{1, 10, 11.2, 5, 5.3, 6.6, 7, 8.8, 'item0', 'item4', 'item5'}
The pop()
method can remove the last item, but since set
s are unordered, there's no way to know which is the last item. The pop()
method returns the removed item.
print(f"set antes de pop(): {set_}")eliminado = set_.pop()print(f"Se ha eliminado {eliminado}")
set antes de pop(): {1, 5, 5.3, 6.6, 8.8, 7, 10, 11.2, 'item5', 'item0', 'item4'}Se ha eliminado 1
The clear()
method can be used to empty the set.
set_.clear()set_
set()
Lastly, with del
you can delete the set
del set_if 'set_' not in locals():print("set eliminado")
set eliminado
2.5.1.3. Unir ítems
a way to unite sets is through the union()
method
set1 = {"a", "b" , "c"}set2 = {1, 2, 3}set3 = set1.union(set2)set3
{1, 2, 3, 'a', 'b', 'c'}
Another way is through the update()
method, but this way adds a set to another, it doesn't create a new one.
set1 = {"a", "b" , "c"}set2 = {1, 2, 3}set1.update(set2)set1
{1, 2, 3, 'a', 'b', 'c'}
These methods of union remove the duplicates, but if we want to get the duplicated elements in two sets we can use the intersection()
method.
set1 = {"apple", "banana", "cherry"}set2 = {"google", "microsoft", "apple"}set3 = set1.intersection(set2)set3
{'apple'}
If we want to get the duplicate elements in two sets, but without creating a new set, we can use the intersection_update()
method.
set1 = {"apple", "banana", "cherry"}set2 = {"google", "microsoft", "apple"}set1.intersection_update(set2)set1
{'apple'}
Now, if we want to get rid of the duplicates, we can use the symmetric_difference()
method.
The difference between this and the union of two sets is that in the union, all items are included, but duplicates are only taken once. Now we keep only those that are not duplicated.
set1 = {"apple", "banana", "cherry"}set2 = {"google", "microsoft", "apple"}set3 = set1.symmetric_difference(set2)set3
{'banana', 'cherry', 'google', 'microsoft'}
If we want to remove the duplicates without creating a new set, we use the symmetric_difference_update()
method.
set1 = {"apple", "banana", "cherry"}set2 = {"google", "microsoft", "apple"}set1.symmetric_difference_update(set2)set1
{'banana', 'cherry', 'google', 'microsoft'}
2.5.1.4. Methods of sets
These are the methods that can be used with sets.
2.5.2. FrozenSet
The frozenset
s are like set
s but with the safety that they are immutable, just as tuple
s are like list
s but immutable. Therefore, we cannot add or remove items.
2.6. Booleans
There are only two booleans in Python: True
and False
The function bool()
can evaluate if anything is True
or False
.
print(bool("Hello"))print(bool(15))print(bool(0))
TrueTrueFalse
2.6.1. Other Data Types True and False
The following data are True
:
- Any string that is not empty
- Any number except 0
- Any list, tuple, dictionary, or set that is not empty
print(bool("Hola"))print(bool(""))
TrueFalse
print(bool(3))print(bool(0))
TrueFalse
lista = [1, 2, 3]print(bool(lista))lista = []print(bool(lista))
TrueFalse
tupla = (1, 2, 3)print(bool(tupla))tupla = ()print(bool(tupla))
TrueFalse
diccionario = {"brand": "Ford","model": "Mustang","year": 1964,"colors": ["red", "white", "blue"]}print(bool(diccionario))diccionario.clear()print(bool(diccionario))
TrueFalse
set_ = {'item0', 1, 5.3, "item4", 5, 6.6}print(bool(set_))set_.clear()print(bool(set_))
TrueFalse
2.7. Binaries
2.7.1. Bytes
The bytes
type is an immutable sequence of bytes. It only accepts ASCII characters. Bytes can also be represented using integers whose values must satisfy 0 <= x < 256
.
To create a byte type, we must introduce the character b
byte = b"MaximoFN"byte
b'MaximoFN'
It can also be created using its constructor bytes()
byte = bytes(10)byte
b'