Many ways to store data
In this article you'll find:
- Introduction
- What is a list?
- What is a dictionary?
- What is a tuple?
- What is a set?
Greetings to all! We have already gone through conditionals, for loops and while loops, however, we still need to take a step back and learn about iterable objects. What is an iterable object?
An iterable object is an object whose elements can be traversed one by one with the use of a loop. Among these, we can find:
- Lists
- Dictionaries
- Tuples
- String
- Sets
And many more. In this post we will go through the first three, so that we know what differentiates each one from the other, besides a parenthesis, a bracket or a brace.
Let's begin!
What is a list?
Lists are data types that allow us to store different elements within a single variable, each one being stored in a particular position with an index.
list = [item1, item2, item3]
As you can see, these are created with square brackets, and the attributes that define it are:
- The lists are ordered.
- Lists can be changed.
- Lists allow duplicates.
Lists are sorted, since each element within them has a specific index, which starts at 0 for the first item. This order cannot be changed, because if a new item is added, it will be added at the end of the list.
list = [item1, item2, item3]
print(list[0])
>>> item1
print(list[1])
>>>>item2
print(list[2])
>>>>item3
Lists can be changed, since the items in the list can be added, modified and deleted without any problem.
list[1] = new_item
print(list)
>>> [item1, new_item, item3]
Lists allow duplicates, since due to their index order, you can have two elements with the same value in different indexes.
list.append(item4)
print(list)
>>> [item1, item2, item3, item4]
What is a dictionary?
While lists are used to store data by index, dictionaries store this information in key:value pairs What does this mean? Take a look at the following example:
thisdict = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Here, we can see that the dictionary, defined with braces, has, in its elements, the pairs "key" and "value", where the key represents an identifier for the value. If we wanted to enter "value1", we only have to write:
print(thisdict["key1"])
>>> value1
Now, among the characteristics of the dictionaries we have:
- Dictionaries are sorted.
- The dictionaries can be changed.
- The dictionaries do not allow duplicates.
Dictionaries have a defined order, which cannot be changed. If you want to add a new key:value pair, it will be placed at the end. However, specific elements cannot be accessed by using indexes as in lists.
Dictionaries can also be added, changed and removed. For this we only have to indicate the key of the element we want to change.
We cannot have elements with the same key name. This means that if we type between the elements "year": "2021" and then type again "year": "2023", only the first pair will be displayed.
What is a tuple?
Like lists and dictionaries, tuples allow a large amount of data to be stored in a single variable. In this case, they are defined with parentheses.
tuple1 = ('value1','value2','value3')
The defining characteristics are:
- Tuples are ordered.
- The tuples cannot be changed.
- Tuples allow duplicate values.
Like lists, tuples are ordered by positions that we can enter with indexes (tuple1[0], tuple1[1]...).
Once we define the values in our tuple, we cannot change them, remove them or add new values. This is why it is unchangeable.
By having index, the tuples can have the same value repeated.
What is a set?
What differentiates the set from the rest of the iterables is not only the use of braces:
set1 = {item1, item2, item3}
But also the fact that:
- They are not ordered
- They cannot be changed, but can be added or removed.
- They do not allow duplicate values
The items in the set have no defined order. This means that they can have a different order each time they are used and that the items cannot be accessed with keys or indexes.
Because we have no way of referencing the items within the set, we cannot modify them, but we can remove them and even add new items.
Like dictionaries, in the absence of an index, the values inside the set cannot be duplicated.
Thus, we can conclude that the main differences between each iterable are:
- Lists are ordered, changeable and allow duplicates.
- The dictionaries are not ordered, are changeable and do not allow duplicates.
- Tuples are ordered, are not changeable and allow duplicates.
- Sets are unordered, partially unchangeable and do not allow duplicates.
Thus, we already know each of the Data-Types that allow us to store a large amount of data in a single variable. I hope this information has been helpful and that you now know them like the back of your hand.
However, if you want to know more about the use of lists, tuples, dictionaries and sets in python, visit the following article by geeksforgeeks
Thanks for your support and good luck!
Diferentes formas de almacenar información
En este artículo encontrarás:
- Introducción
- ¿Qué es una lista?
- ¿Qué es un diccionario?
- ¿Qué es una tupla?
- ¿Qué es un set?
Un saludo a todos! Ya hemos pasado por los condicionales, los bucles for y los bucles while, sin embargo, aún nos falta dar un paso atrás y conocer a los objetos iterables. ¿Qué es un objeto iterable?
Un objeto iterable es aquel cuyos elementos pueden ser recorridos uno por uno con el uso de un bucle. Entre estos, podemos encontrar:
- Listas
- Diccionarios
- Tuplas
- String
Y muchas más. En este post iremos por las primeras tres, de forma que sepamos que diferencia a cada una de la otra, además de un paréntesis, un corchete o una llave.
¡Comencemos!
¿Qué es una lista?
Las listas son data types que nos permiten almacenar distintos elementos dentro de una sola variable, siendo cada uno de guardado en una posición partícular con un índice.
lista = [item1, item2, item3]
Como puedes observar, estas se crean con corchetes cuadrados, y los atributos que la definen son:
- Las listas están ordenadas.
- Las listas pueden ser cambiadas
- Las listas permiten duplicados.
Las listas están ordenadas, ya que cada elemento dentro de estas tiene un índice específico, que comienza en 0 para el primer item. Este orden no puede cambiarse, ya que si agregamos un nuevo elemento, este se añadirá al final de la lista.
list = [item1, item2, item3]
print(list[0])
>>> item1
print(list[1])
>>>item2
print(list[2])
>>>item3
Las listas pueden ser cambiadas, ya que los elementos en esta pueden ser añadidos, modificados y eliminados sin problema.
list[1] = new_item
print(list)
>>> [item1, new_item, item3]
Las listas permiten duplicados, ya que debido a su orden por índices, se pueden tener dos elementos con el mismo valor en distintos índices.
list.append(item4)
print(list)
>>> [item1, item2, item3, item4]
¿Qué es un diccionario?
Mientras las listas son empleadas para guardar datos por índices, los diccionarios almacenan esta información en pares llave:valor ¿Qué quiere decir esto? Echa un vistazo al siguiente ejemplo
thisdict = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Aquí, podemos ver que el diccionario, definido con llaves, tiene, en sus elementos, los pares "key" y "value", donde el key representa un identificador para el valor. Si quisieramos ingresar a "value1", solo tenemos que escribir:
print(thisdict["key1"])
>>> value1
Ahora, entre las características de los diccionarios tenemos:
- Los diccionarios están ordenados.
- Los diccionarios pueden ser cambiados.
- Los diccionarios no permiten duplicados.
Los diccionarios tienen un orden definido, que no puede ser cambiado. Si quieres añadir un nuevo par llave:valor, este se colocará al final. Sin embargo, no se pueden acceder a elementos específicos por medio del uso de índices como en las listas.
Los diccionarios también pueden ser añadidos, cambiados y removidos. Para esto solo debemos de indicar la llave del elemento que queramos cambiar.
No podemos tener elementos con el mismo nombre de llave. Esto significa que si escribimos entre los elementos "year":"2021" y luego volvemos a escribir "year":"2023", solo se mostrará el primer par se mostrará.
¿Qué es una tupla?
Al igual que las listas y los diccionarios, las tuplas permiten almacenar gran cantidad de datos en una sola variable. En este caso, estas se definen con paréntesis.
tuple1 = ('value1','value2','value3')
Las características que la definen son:
- Las tuplas están ordenadas.
- Las tuplas no pueden ser cambiadas.
- Las tuplas permiten valores duplicados.
Al igual que las listas, las tuplas están ordenadas por posiciones a las que podemos ingresar con índices (tuple1[0], tuple1[1]...).
Una vez que definimos los valores en nuestra tupla, no podremos cambiarlos, removerlos o añadir nuevos valores. Es por esto que es incambiable.
Al tener índice, las tuplas pueden tener el mismo valor repetido.
¿Qué es un set?
Lo que diferencia al set del resto de los iterables no solo es el uso de llaves:
set1 = {item1, item2, item3}
Sino también el hecho de que:
- No están ordenados
- No pueden ser cambiados, pero si añadidos o removidos.
- No permiten valores duplicados
Los items del set no tienen un orden definido. Esto significa que pueden tener un orden distinto cada vez que sean usados y que no se puede acceder a los elementos por medio de llaves o índices.
Debido a que no tenemos forma de referenciar a los elementos dentro del set, no podemos modificarlos, más si podemos removerlos e incluso añadir nuevos elementos.
Al igual que los diccionarios, a falta de índice, los valores dentro de los set no pueden ser duplicados.
Así, podemos concluir que las principales diferencias entre cada iterable son:
- Las listas son ordenadas, cambiables y permiten duplicados.
- Los diccionarios no son ordenados, son cambiables y no permiten duplicados.
- Las tuplas son ordenadas, no son cambiables y permiten duplicados.
- Los set no son ordenados, son parcialmente incambiables y no permiten duplicados.
De esta forma, ya conocemos cada uno de los Data-Types que nos permiten almacenar gran cantidad de datos en una sola variable. Espero que esta información te haya sido de ayuda y que ahora conozcas estos como la palma de tu mano.
Sin embargo, si quieres saber más sobre el uso de listas, tuplas, diccionarios y sets en python, visita el siguiente artículo por geeksforgeeks
¡Gracias por tu apoyo y buena suerte!