Complete Python Guide 2025 (1/3): data types

Complete Python Guide 2025 (1/3): data types

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. Summarylink image 45

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.

python

2. Python Data Typeslink image 46

There are 7 types of data in Python

  1. Text type: str
  2. Numeric: int, float, complex
  3. Sequences: list, tuple, range
  4. Mapping: dict5. Conjuntos: set, frozenset
  5. Booleans: bool
  6. Binary: bytes, bytearray, memoryview

We can obtain the data type using the type() function

	
< > Input
Python
type(5.)
Copied
>_ Output
			
float

Python is a dynamically typed language, that is, you can have a variable of one type and then assign it another type

	
< > Input
Python
a = 5
type(a)
Copied
>_ Output
			
int
	
< > Input
Python
a = 'MaximoFN'
type(a)
Copied
>_ Output
			
str

Python infers variable types for you, but if you want to type them yourself, you can do so

	
< > Input
Python
b = int(5.1)
type(b), b
Copied
>_ Output
			
(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. Cadenaslink image 47

strings are character strings; these can be defined with double quotes " or single quotes '

	
< > Input
Python
string = "MaximoFN"
string
Copied
>_ Output
			
'MaximoFN'
	
< > Input
Python
string = 'MaximoFN'
string
Copied
>_ Output
			
'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

	
< > Input
Python
string = """Este es un ejemplo de
como estoy introduciendo un string
en varias lineas"""
string
Copied
>_ Output
			
'Este es un ejemplo de como estoy introduciendo un string en varias lineas'
	
< > Input
Python
string = '''Este es un ejemplo de
como estoy introduciendo un string
en varias lineas'''
string
Copied
>_ Output
			
'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

	
< > Input
Python
print(string)
Copied
>_ Output
			
Este es un ejemplo de
como estoy introduciendo un string
en varias lineas

As we have said, strings are sequences of characters, so we can navigate and iterate through them

	
< > Input
Python
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 linea
print(string[i], end='')
Copied
>_ Output
			
Este es un

We can obtain the length of our string using the len() function

	
< > Input
Python
len(string)
Copied
>_ Output
			
73

Check if there is any specific string within ours

	
< > Input
Python
'ejemplo' in string
Copied
>_ Output
			
True

Strings have certain useful attributes, such as putting everything in uppercase

	
< > Input
Python
print(string.upper())
Copied
>_ Output
			
ESTE ES UN EJEMPLO DE
COMO ESTOY INTRODUCIENDO UN STRING
EN VARIAS LINEAS

all in lowercase

	
< > Input
Python
print(string.lower())
Copied
>_ Output
			
este es un ejemplo de
como estoy introduciendo un string
en varias lineas

Replace characters

	
< > Input
Python
print(string.replace('o', '@'))
Copied
>_ Output
			
Este es un ejempl@ de
c@m@ est@y intr@duciend@ un string
en varias lineas

Get all the words

	
< > Input
Python
print(string.split())
Copied
>_ Output
			
['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

	
< > Input
Python
string1 = 'Maximo'
string2 = 'FN'
string1 + string2
Copied
>_ Output
			
'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 \"

	
< > Input
Python
print("Este es el blog de "MaximoFN"")
Copied
>_ Output
			
Este es el blog de "MaximoFN"

The same applies to the single quote, we add \'

	
< > Input
Python
print('Este es el blog de 'MaximoFN'')
Copied
>_ Output
			
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 \

	
< > Input
Python
print('Este es el blog de \\MaximoFN\\')
Copied
>_ Output
			
Este es el blog de \MaximoFN\

We already saw the newline escape character \n before

	
< > Input
Python
print('Este es el blog de \nMaximoFN')
Copied
>_ Output
			
Este es el blog de
MaximoFN

If we want to write from the beginning of the line, we add \r

	
< > Input
Python
print('Esto no se imprimirá \rEste es el blog de MaximoFN')
Copied
>_ Output
			
Este es el blog de MaximoFN

If we want to add a large space (indentation), we use \t

	
< > Input
Python
print('Este es el blog de \tMaximoFN')
Copied
>_ Output
			
Este es el blog de MaximoFN

We can delete a character with \b

	
< > Input
Python
print('Este es el blog de \bMaximoFN')
Copied
>_ Output
			
Este es el blog deMaximoFN

We can add the ASCII code in octal using \ooo

	
< > Input
Python
print('\115\141\170\151\155\157\106\116')
Copied
>_ Output
			
MaximoFN

Or add the ASCII code in hexadecimal using \xhh

	
< > Input
Python
print('\x4d\x61\x78\x69\x6d\x6f\x46\x4e')
Copied
>_ Output
			
MaximoFN

Lastly, we can convert another data type into a string

	
< > Input
Python
n = 5
print(type (n))
string = str(n)
print(type(string))
Copied
>_ Output
			
&lt;class 'int'&gt;
&lt;class 'str'&gt;

2.2. Numberslink image 48

2.2.1. Integerslink image 49

Integers of the integer type

	
< > Input
Python
n = 5
n, type(n)
Copied
>_ Output
			
(5, int)

2.2.2. Floatlink image 50

Floating-point numbers

	
< > Input
Python
n = 5.1
n, type(n)
Copied
>_ Output
			
(5.1, float)

2.2.3. Complex numberslink image 51

Complex numbers

	
< > Input
Python
n = 3 + 5j
n, type(n)
Copied
>_ Output
			
((3+5j), complex)

2.2.4. Conversionlink image 52

Can numbers be converted between types

	
< > Input
Python
n = 5
n = float(n)
n, type(n)
Copied
>_ Output
			
(5.0, float)
	
< > Input
Python
n = 5.1
n = complex(n)
n, type(n)
Copied
>_ Output
			
((5.1+0j), complex)
	
< > Input
Python
n = 5.1
n = int(n)
n, type(n)
Copied
>_ Output
			
(5, int)

A complex number cannot be converted to int or float type

2.3. Sequenceslink image 53

2.3.1. Listslink image 54

Lists store multiple items in a variable. They are declared using the symbols [], with the items separated by commas

	
< > Input
Python
lista = ['item0', 'item1', 'item2', 'item3', 'item4', 'item5']
lista
Copied
>_ Output
			
['item0', 'item1', 'item2', 'item3', 'item4', 'item5']

We can obtain the length of a list using the len() function

	
< > Input
Python
len(lista)
Copied
>_ Output
			
6

Lists can have items of different types

	
< > Input
Python
lista = ['item0', 1, True, 5.3, "item4", 5, 6.6]
lista
Copied
>_ Output
			
['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

	
< > Input
Python
lista[0]
Copied
>_ Output
			
'item0'

But one of the powerful things about Python is that if we want to access the last position, we can use negative indices

	
< > Input
Python
lista[-1]
Copied
>_ Output
			
6.6

If instead of the last position in the list, we want the second-to-last one

	
< > Input
Python
lista[-2]
Copied
>_ Output
			
5

If we only want a range of values, for example, from the second to the fifth item, we access it using [2:5]

	
< > Input
Python
lista[2:5]
Copied
>_ Output
			
[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]

	
< > Input
Python
lista[:5]
Copied
>_ Output
			
['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:]

	
< > Input
Python
lista[3:]
Copied
>_ Output
			
[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.

	
< > Input
Python
lista[-3:-1]
Copied
>_ Output
			
['item4', 5]

Can you check if an item is in the list

	
< > Input
Python
'item4' in lista
Copied
>_ Output
			
True
2.3.1.1. Edit listslink image 55

Python lists are dynamic, that is, they can be modified. For example, the third item can be modified

	
< > Input
Python
lista[2] = False
lista
Copied
>_ Output
			
['item0', 1, False, 5.3, 'item4', 5, 6.6]

It is also possible to modify a range of values

	
< > Input
Python
lista[1:4] = [1.1, True, 3]
lista
Copied
>_ Output
			
['item0', 1.1, True, 3, 'item4', 5, 6.6]

Values can be added to the end of the list using the append() method

	
< > Input
Python
lista.append('item7')
lista
Copied
>_ Output
			
['item0', 1.1, True, 3, 'item4', 5, 6.6, 'item7']

Or we can insert a value at a specific position using the insert() method

	
< > Input
Python
lista.insert(2, 'insert')
lista
Copied
>_ Output
			
['item0', 1.1, 'insert', True, 3, 'item4', 5, 6.6, 'item7']

Can lists be combined using the extend() method

	
< > Input
Python
lista2 = ['item8', 'item9']
lista.extend(lista2)
lista
Copied
>_ Output
			
['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.)

	
< > Input
Python
tupla = ('item10', 'item11')
lista.extend(tupla)
lista
Copied
>_ Output
			
['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

	
< > Input
Python
lista.pop(2)
lista
Copied
>_ Output
			
['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

	
< > Input
Python
lista.pop()
lista
Copied
>_ Output
			
['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

	
< > Input
Python
lista.remove('item7')
lista
Copied
>_ Output
			
['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

	
< > Input
Python
del lista[3]
lista
Copied
>_ Output
			
['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

	
< > Input
Python
lista.clear()
lista
Copied
>_ Output
			
[]

Can the number of items with a given value be obtained using the count() method?

	
< > Input
Python
lista = [5, 4, 6, 5, 7, 8, 5, 3, 1, 5]
lista.count(5)
Copied
>_ Output
			
4

You can also obtain the first index of an item with a given value using the index() method.

	
< > Input
Python
lista = [5, 4, 6, 5, 7, 8, 5, 3, 1, 5]
lista.index(5)
Copied
>_ Output
			
0
2.3.1.2. Comprensión de listaslink image 56

We can operate through the list

	
< > Input
Python
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
# Iteramos por todos los items de la lista
for x in fruits:
# Si el item contiene el caracter "a" lo añadimos a newlist
if "a" in x:
newlist.append(x)
newlist
Copied
>_ Output
			
['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

	
< > Input
Python
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
newlist
Copied
>_ Output
			
['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

	
< > Input
Python
newlist = [x.upper() for x in fruits if "a" in x]
newlist
Copied
>_ Output
			
['APPLE', 'BANANA', 'MANGO']
2.3.1.3. Sort listslink image 57

To sort lists, we use the sort() method

	
< > Input
Python
lista = [5, 8, 3, 4, 9, 5, 6]
lista.sort()
lista
Copied
>_ Output
			
[3, 4, 5, 5, 6, 8, 9]

It also sorts them alphabetically

	
< > Input
Python
lista = ["orange", "mango", "kiwi", "pineapple", "banana"]
lista.sort()
lista
Copied
>_ Output
			
['banana', 'kiwi', 'mango', 'orange', 'pineapple']

When sorting alphabetically, distinguish between uppercase and lowercase letters

	
< > Input
Python
lista = ["orange", "mango", "kiwi", "Pineapple", "banana"]
lista.sort()
lista
Copied
>_ Output
			
['Pineapple', 'banana', 'kiwi', 'mango', 'orange']

They can be sorted in descending order using the reverse = True attribute

	
< > Input
Python
lista = [5, 8, 3, 4, 9, 5, 6]
lista.sort(reverse = True)
lista
Copied
>_ Output
			
[9, 8, 6, 5, 5, 4, 3]

They can be sorted in any way we want using the key attribute

	
< > Input
Python
def myfunc(n):
# devuelve el valor absoluto de n - 50
return abs(n - 50)
lista = [100, 50, 65, 82, 23]
lista.sort(key = myfunc)
lista
Copied
>_ Output
			
[50, 65, 23, 82, 100]

Can this be used so that, for example, when sorting, it does not distinguish between uppercase and lowercase letters?

	
< > Input
Python
lista = ["orange", "mango", "kiwi", "Pineapple", "banana"]
lista.sort(key = str.lower)
lista
Copied
>_ Output
			
['banana', 'kiwi', 'mango', 'orange', 'Pineapple']

You can reverse the list using the reverse method

	
< > Input
Python
lista = [5, 8, 3, 4, 9, 5, 6]
lista.reverse()
lista
Copied
>_ Output
			
[6, 5, 9, 4, 3, 8, 5]
2.3.1.4. Copying listslink image 58

Lists cannot be copied using lista1 = lista2, since if lista1 is modified, lista2 is also modified

	
< > Input
Python
lista1 = [5, 8, 3, 4, 9, 5, 6]
lista2 = lista1
lista1[0] = True
lista2
Copied
>_ Output
			
[True, 8, 3, 4, 9, 5, 6]

So, the copy() method should be used.

	
< > Input
Python
lista1 = [5, 8, 3, 4, 9, 5, 6]
lista2 = lista1.copy()
lista1[0] = True
lista2
Copied
>_ Output
			
[5, 8, 3, 4, 9, 5, 6]

Or you have to use the list() constructor

	
< > Input
Python
lista1 = [5, 8, 3, 4, 9, 5, 6]
lista2 = list(lista1)
lista1[0] = True
lista2
Copied
>_ Output
			
[5, 8, 3, 4, 9, 5, 6]
2.3.1.5. Concatenate listslink image 59

Can lists be concatenated using the + operator

	
< > Input
Python
lista1 = [5, 8, 3, 4, 9, 5, 6]
lista2 = ['a', 'b', 'c']
lista = lista1 + lista2
lista
Copied
>_ Output
			
[5, 8, 3, 4, 9, 5, 6, 'a', 'b', 'c']

Or by using the extend method

	
< > Input
Python
lista1 = [5, 8, 3, 4, 9, 5, 6]
lista2 = ['a', 'b', 'c']
lista1.extend(lista2)
lista1
Copied
>_ Output
			
[5, 8, 3, 4, 9, 5, 6, 'a', 'b', 'c']

Another way to concatenate is to repeat the tuple X times using the * operator

	
< > Input
Python
lista1 = ['a', 'b', 'c']
lista2 = lista1 * 3
lista2
Copied
>_ Output
			
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']

2.3.2. Tupleslink image 60

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

	
< > Input
Python
tupla = ('item0', 1, True, 3.3, 'item4', True)
tupla
Copied
>_ Output
			
('item0', 1, True, 3.3, 'item4', True)

Its length can be obtained using the len() function

	
< > Input
Python
len (tupla)
Copied
>_ Output
			
6

To create tuples with a single element, it is necessary to add a comma

	
< > Input
Python
tupla = ('item0',)
tupla, type(tupla)
Copied
>_ Output
			
(('item0',), tuple)

To access an element of the tuple, you do the same as with lists

	
< > Input
Python
tupla = ('item0', 1, True, 3.3, 'item4', True)
print(tupla[0])
print(tupla[-1])
print(tupla[2:4])
print(tupla[-4:-2])
Copied
>_ Output
			
item0
True
(True, 3.3)
(True, 3.3)

Can we check if there is an item in the tuple

	
< > Input
Python
'item4' in tupla
Copied
>_ Output
			
True
2.3.2.1. Modify tupleslink image 61

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

	
< > Input
Python
lista = list(tupla)
lista[4] = 'ITEM4'
tupla = tuple(lista)
tupla
Copied
>_ Output
			
('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

	
< > Input
Python
del tupla
if 'tupla' not in locals():
print("tupla eliminada")
Copied
>_ Output
			
tupla eliminada
2.3.2.2. Unpacking tupleslink image 62

When we create tuples, we are actually packaging data

	
< > Input
Python
tupla = ('item0', 1, True, 3.3, 'item4', True)
tupla
Copied
>_ Output
			
('item0', 1, True, 3.3, 'item4', True)

but we can unpack them

	
< > Input
Python
item0, item1, item2, item3, item4, item5 = tupla
item0, item1, item2, item3, item4, item5
Copied
>_ Output
			
('item0', 1, True, 3.3, 'item4', True)

If we want to extract fewer data than the length of the tuple, we add a *

	
< > Input
Python
item0, item1, item2, *item3 = tupla
item0, item1, item2, item3
Copied
>_ Output
			
('item0', 1, True, [3.3, 'item4', True])

Can the asterisk * be placed somewhere else if, for example, what we want is the last item?

	
< > Input
Python
item0, item1, *item2, item5 = tupla
item0, item1, item2, item5
Copied
>_ Output
			
('item0', 1, [True, 3.3, 'item4'], True)
2.3.2.3. Concatenate tupleslink image 63

Tuples can be concatenated using the + operator

	
< > Input
Python
tupla1 = ("a", "b" , "c")
tupla2 = (1, 2, 3)
tupla3 = tupla1 + tupla2
tupla3
Copied
>_ Output
			
('a', 'b', 'c', 1, 2, 3)

Another way to concatenate is to repeat the tuple X times using the * operator

	
< > Input
Python
tupla1 = ("a", "b" , "c")
tupla2 = tupla1 * 3
tupla2
Copied
>_ Output
			
('a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c')
2.3.2.4. Tuple methodslink image 64

Tuples have two methods, the first is the count() method, which returns the number of times an item appears within the tuple

	
< > Input
Python
tupla = (5, 4, 6, 5, 7, 8, 5, 3, 1, 5)
tupla.count(5)
Copied
>_ Output
			
4

Another method is index() which returns the first position of an item within the tuple

	
< > Input
Python
tupla = (5, 4, 6, 5, 7, 8, 5, 3, 1, 5)
tupla.index(5)
Copied
>_ Output
			
0

2.3.3. Rangelink image 65

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)

	
< > Input
Python
for i in range(5):
print(f'{i} ', end='')
Copied
>_ Output
			
0 1 2 3 4

Yes, for example, if we don't want it to start at 0

	
< > Input
Python
for i in range(2, 5):
print(f'{i} ', end='')
Copied
>_ Output
			
2 3 4
	
< > Input
Python
for i in range(-2, 5):
print(f'{i} ', end='')
Copied
>_ Output
			
-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.

	
< > Input
Python
for i in range(0, 10, 2):
print(f'{i} ', end='')
Copied
>_ Output
			
0 2 4 6 8

2.4. Dictionarieslink image 66

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.

	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"colors": ["red", "white", "blue"]
}
diccionario
Copied
>_ Output
			
{'brand': 'Ford',
'model': 'Mustang',
'year': 1964,
'colors': ['red', 'white', 'blue']}

As stated, they do not allow duplicates

	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2000,
"colors": ["red", "white", "blue"]
}
diccionario["year"]
Copied
>_ Output
			
2000

Its length can be obtained using the len() function.

	
< > Input
Python
len(diccionario)
Copied
>_ Output
			
4

As can be seen, the length is 4 and not 5, since year is counted only once

2.4.1. Accessing itemslink image 67

To access an element, we can do it through its key

	
< > Input
Python
diccionario["model"]
Copied
>_ Output
			
'Mustang'

It can also be accessed using the get method

	
< > Input
Python
diccionario.get("model")
Copied
>_ Output
			
'Mustang'

To know all the keys of the dictionaries, you can use the keys() method

	
< > Input
Python
diccionario.keys()
Copied
>_ Output
			
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

	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# Se declara una vez la variable que apunta a las keys
x = diccionario.keys()
print(x)
# Se añade una nueva key
diccionario["color"] = "white"
# Se consulta la variable que apunta a las key
print(x)
Copied
>_ Output
			
dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year', 'color'])

To obtain the values from the dictionary, you can use the values() method.

	
< > Input
Python
diccionario.values()
Copied
>_ Output
			
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

	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# Se declara una vez la variable que apunta a los values
x = diccionario.values()
print(x)
# Se modifica un value
diccionario["year"] = 2020
# Se consulta la variable que apunta a los values
print(x)
Copied
>_ Output
			
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

	
< > Input
Python
diccionario.items()
Copied
>_ Output
			
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

	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# Se declara una vez la variable que apunta a los items
x = diccionario.items()
print(x)
# Se modifica un value
diccionario["year"] = 2020
# Se consulta la variable que apunta a los items
print(x)
Copied
>_ Output
			
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

	
< > Input
Python
"model" in diccionario
Copied
>_ Output
			
True

2.4.2. Modify the itemslink image 68

Can an item be modified by accessing it directly

	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# Se modifica un item
diccionario["year"] = 2020
diccionario
Copied
>_ Output
			
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Or it can be modified using the update() method

	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# Se modifica un item
diccionario.update({"year": 2020})
diccionario
Copied
>_ Output
			
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

2.4.3. Add itemslink image 69

You can add an item by adding it in this way:

	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# Se modifica un item
diccionario["colour"] = "blue"
diccionario
Copied
>_ Output
			
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'colour': 'blue'}

Or it can be added using the update() method

	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# Se modifica un item
diccionario.update({"colour": "blue"})
diccionario
Copied
>_ Output
			
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'colour': 'blue'}

2.4.4. Remove itemslink image 70

Can an item with a specific key be removed using the pop() method?

	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# Se elimina un item
diccionario.pop("model")
diccionario
Copied
>_ Output
			
{'brand': 'Ford', 'year': 1964}

Or you can delete an item with a specific key using del, specifying the key name between the [] symbols

	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# Se elimina un item
del diccionario["model"]
diccionario
Copied
>_ Output
			
{'brand': 'Ford', 'year': 1964}

The entire dictionary is deleted if del is used and the key of an item is not specified

	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# Se elimina un item
del diccionario
if 'diccionario' not in locals():
print("diccionario eliminado")
Copied
>_ Output
			
diccionario eliminado

If what you want is to delete the last item entered, you can use the popitem() method

	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# Se elimina el último item introducido
diccionario.popitem()
diccionario
Copied
>_ Output
			
{'brand': 'Ford', 'model': 'Mustang'}

If you want to clear the dictionary, you should use the clear() method

	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
diccionario.clear()
diccionario
Copied
>_ Output
			
{}

2.4.5. Copying dictionarieslink image 71

Dictionaries cannot be copied with diccionario1 = diccionario2, since if diccionario1 is modified, diccionario2 is also modified

	
< > Input
Python
diccionario1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
diccionario2 = diccionario1
diccionario1["year"] = 2000
diccionario2["year"]
Copied
>_ Output
			
2000

So the copy() method has to be used

	
< > Input
Python
diccionario1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
diccionario2 = diccionario1.copy()
diccionario1["year"] = 2000
diccionario2["year"]
Copied
>_ Output
			
1964

Or you have to use the dict() dictionary constructor

	
< > Input
Python
diccionario1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
diccionario2 = dict(diccionario1)
diccionario1["year"] = 2000
diccionario2["year"]
Copied
>_ Output
			
1964

2.4.6. Nested dictionarieslink image 72

Dictionaries can have items of any data type, even other dictionaries. This type of dictionary is called nested dictionaries.

	
< > Input
Python
diccionario_nested = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
diccionario_nested
Copied
>_ Output
			
{'child1': {'name': 'Emil', 'year': 2004},
'child2': {'name': 'Tobias', 'year': 2007},
'child3': {'name': 'Linus', 'year': 2011}}
	
< > Input
Python
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
Copied
>_ Output
			
{'child1': {'name': 'Emil', 'year': 2004},
'child2': {'name': 'Tobias', 'year': 2007},
'child3': {'name': 'Linus', 'year': 2011}}

2.4.7. Dictionary methodslink image 73

These are the methods that can be used in dictionaries

2.4.8. Comprensión de diccionarioslink image 74

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

	
< > Input
Python
dictionary_comprehension = {x: x**2 for x in (2, 4, 6) if x &gt; 2}
dictionary_comprehension
Copied
>_ Output
			
{4: 16, 6: 36}

2.5. Setslink image 75

2.5.1. Setlink image 76

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_

	
< > Input
Python
set_ = {'item0', 1, 5.3, "item4", 5, 6.6}
set_
Copied
>_ Output
			
{1, 5, 5.3, 6.6, 'item0', 'item4'}

There cannot be duplicate items; if any duplicate item is found, only one is kept

	
< > Input
Python
set_ = {'item0', 1, 5.3, "item4", 5, 6.6, 'item0'}
set_
Copied
>_ Output
			
{1, 5, 5.3, 6.6, 'item0', 'item4'}

Can you get the length of the set using the len() function?

	
< > Input
Python
len(set_)
Copied
>_ Output
			
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

	
< > Input
Python
'item4' in set_
Copied
>_ Output
			
True
2.5.1.1. Add itemslink image 77

Can an element be added to the set using the add() method?

	
< > Input
Python
set_.add(8.8)
set_
Copied
>_ Output
			
{1, 5, 5.3, 6.6, 8.8, 'item0', 'item4'}

Can another set be added through the update() method?

	
< > Input
Python
set2 = {"item5", "item6", 7}
set_.update(set2)
set_
Copied
>_ Output
			
{1, 5, 5.3, 6.6, 7, 8.8, 'item0', 'item4', 'item5', 'item6'}

Items from Python iterable data types can also be added

	
< > Input
Python
lista = ["item9", 10, 11.2]
set_.update(lista)
set_
Copied
>_ Output
			
{1, 10, 11.2, 5, 5.3, 6.6, 7, 8.8, 'item0', 'item4', 'item5', 'item6', 'item9'}
2.5.1.2. Remove itemslink image 78

A specific item can be removed using the remove() method

	
< > Input
Python
set_.remove('item9')
set_
Copied
>_ Output
			
{1, 10, 11.2, 5, 5.3, 6.6, 7, 8.8, 'item0', 'item4', 'item5', 'item6'}

Or by using the discard() method

	
< > Input
Python
set_.discard('item6')
set_
Copied
>_ Output
			
{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

	
< > Input
Python
print(f"set antes de pop(): {set_}")
eliminado = set_.pop()
print(f"Se ha eliminado {eliminado}")
Copied
>_ Output
			
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

	
< > Input
Python
set_.clear()
set_
Copied
>_ Output
			
set()

Finally, with del you can remove the set

	
< > Input
Python
del set_
if 'set_' not in locals():
print("set eliminado")
Copied
>_ Output
			
set eliminado
2.5.1.3. Merge itemslink image 79

One way to join sets is by using the union() method

	
< > Input
Python
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
set3
Copied
>_ Output
			
{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

	
< > Input
Python
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
set1
Copied
>_ Output
			
{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.

	
< > Input
Python
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1.intersection(set2)
set3
Copied
>_ Output
			
{'apple'}

If we want to obtain the duplicate elements in two sets, but without creating a new set, we use the intersection_update() method

	
< > Input
Python
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set1.intersection_update(set2)
set1
Copied
>_ Output
			
{'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.

	
< > Input
Python
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1.symmetric_difference(set2)
set3
Copied
>_ Output
			
{'banana', 'cherry', 'google', 'microsoft'}

If we want to keep the non-duplicates without creating a new set, we use the symmetric_difference_update() method

	
< > Input
Python
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set1.symmetric_difference_update(set2)
set1
Copied
>_ Output
			
{'banana', 'cherry', 'google', 'microsoft'}
2.5.1.4. Set methodslink image 80

These are the methods that can be used in sets

2.5.2. FrozenSetlink image 81

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. Booleanslink image 82

There are only two booleans in Python: True and False

Using the bool() function, you can evaluate whether anything is True or False

	
< > Input
Python
print(bool("Hello"))
print(bool(15))
print(bool(0))
Copied
>_ Output
			
True
True
False

2.6.1. Other data types True and Falselink image 83

The following data are True:

  • Any non-empty string
  • Any number except 0* Any non-empty list, tuple, dictionary, or set
	
< > Input
Python
print(bool("Hola"))
print(bool(""))
Copied
>_ Output
			
True
False
	
< > Input
Python
print(bool(3))
print(bool(0))
Copied
>_ Output
			
True
False
	
< > Input
Python
lista = [1, 2, 3]
print(bool(lista))
lista = []
print(bool(lista))
Copied
>_ Output
			
True
False
	
< > Input
Python
tupla = (1, 2, 3)
print(bool(tupla))
tupla = ()
print(bool(tupla))
Copied
>_ Output
			
True
False
	
< > Input
Python
diccionario = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(bool(diccionario))
diccionario.clear()
print(bool(diccionario))
Copied
>_ Output
			
True
False
	
< > Input
Python
set_ = {'item0', 1, 5.3, "item4", 5, 6.6}
print(bool(set_))
set_.clear()
print(bool(set_))
Copied
>_ Output
			
True
False

2.7. Binarieslink image 84

2.7.1. Byteslink image 85

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

	
< > Input
Python
byte = b"MaximoFN"
byte
Copied
>_ Output
			
b'MaximoFN'

They can also be created using their bytes() constructor

	
< > Input
Python
byte = bytes(10)
byte
Copied
>_ Output
			
b''
	
< > Input
Python
byte = bytes(range(10))
byte
Copied
>_ Output
			
b' '

Can bytes be concatenated using the + operator

	
< > Input
Python
byte1 = b'DeepMax'
byte2 = b'FN'
byte3 = byte1 + byte2
byte3
Copied
>_ Output
			
b'DeepMaxFN'

Or by repetition with the * operator

	
< > Input
Python
byte1 = b'MaximoFN '
byte2 = byte1 * 3
byte2
Copied
>_ Output
			
b'MaximoFN MaximoFN MaximoFN '

We can check if a character is within the string

	
< > Input
Python
b'D' in byte1
Copied
>_ Output
			
False

These are the methods that can be used on bytes

2.7.2. Bytearraylink image 86

bytearrays are the same as bytes, except that they are mutable

	
< > Input
Python
byte_array = bytearray(b'MaximoFN')
byte_array
Copied
>_ Output
			
bytearray(b'MaximoFN')

2.7.3. MemoryViewlink image 87

The memoryview objects allow Python code to access the internal data of an object that supports the buffer protocol without making copies.

The memoryview() function allows direct read and write access to the byte-oriented data of an object without needing to copy it first. This can provide significant performance gains when working with large objects, since it does not create a copy when slicing.

Buffer protocol, you can create another access object to modify large data without copying it. This makes the program use less memory and increases execution speed.

	
< > Input
Python
byte_array = bytearray('XYZ', 'utf-8')
print(f'Antes de acceder a la memoria: {byte_array}')
mem_view = memoryview(byte_array)
mem_view[2]= 74
print(f'Después de acceder a la memoria: {byte_array}')
Copied
>_ Output
			
Antes de acceder a la memoria: bytearray(b'XYZ')
Después de acceder a la memoria: bytearray(b'XYJ')

---

➡️ **Continue in Part 2: operators, control flow, and functions**, where you will learn to work with data and structure your code with functions.

Full series

Frequently asked questions

Why does modifying lista1 also change lista2 after doing lista2 = lista1 in Python?

Because lista2 = lista1 doesn't copy the list, it just copies the reference, so both variables point to the same object in memory. That's why after lista1 = [5, 8, 3, 4, 9, 5, 6]; lista2 = lista1; lista1[0] = True, printing lista2 also shows True in the first position. To actually copy it, use lista2 = lista1.copy() or lista2 = list(lista1).

Why does tupla = ('item0',) need that trailing comma?

Because without the comma, ('item0') is just the string 'item0' wrapped in parentheses (a grouped expression), not a tuple. Python identifies tuples by the comma, not the parentheses, so to create a single-element tuple you must write tupla = ('item0',); if you drop the comma and check type(tupla), you'd get str instead of tuple.

Continue reading

Last posts -->

Have you seen these projects?

Gymnasia

Gymnasia Gymnasia
React Native
Expo
TypeScript
FastAPI
Next.js
OpenAI
Anthropic

Mobile personal training app with AI assistant, exercise library, workout tracking, diet and body measurements

Horeca chatbot

Horeca chatbot Horeca chatbot
Python
LangChain
PostgreSQL
PGVector
React
Kubernetes
Docker
GitHub Actions

Chatbot conversational for cooks of hotels and restaurants. A cook, kitchen manager or room service of a hotel or restaurant can talk to the chatbot to get information about recipes and menus. But it also implements agents, with which it can edit or create new recipes or menus

View all projects -->
>_ Available for projects

Do you have an AI project?

Let's talk.

maximofn@gmail.com

Machine Learning and AI specialist. I develop solutions with generative AI, intelligent agents and custom models.

Do you want to watch any talk?

Last talks -->

Do you want to improve with these tips?

Last tips -->

Use this locally

Hugging Face spaces allow us to run models with very simple demos, but what if the demo breaks? Or if the user deletes it? That's why I've created docker containers with some interesting spaces, to be able to use them locally, whatever happens. In fact, if you click on any project view button, it may take you to a space that doesn't work.

Flow edit

Flow edit Flow edit

FLUX.1-RealismLora

FLUX.1-RealismLora FLUX.1-RealismLora
View all containers -->
>_ Available for projects

Do you have an AI project?

Let's talk.

maximofn@gmail.com

Machine Learning and AI specialist. I develop solutions with generative AI, intelligent agents and custom models.

Do you want to train your model with these datasets?

short-jokes-dataset

HuggingFace

Dataset with jokes in English

Use: Fine-tuning text generation models for humor

231K rows 2 columns 45 MB
View on HuggingFace →

opus100

HuggingFace

Dataset with translations from English to Spanish

Use: Training English-Spanish translation models

1M rows 2 columns 210 MB
View on HuggingFace →

netflix_titles

HuggingFace

Dataset with Netflix movies and series

Use: Netflix catalog analysis and recommendation systems

8.8K rows 12 columns 3.5 MB
View on HuggingFace →
View more datasets -->