post.append(upvote)
Shoutout to Python in Plain English
In this article you'll find:
- Introduction
- How to Access Items on Lists
- How to Change Items on Lists
- How to Add Items to Lists
- How to remove Items from Lists
In a previous article, I talked about lists and other types of DataTypes that allow us to store a large amount of data in a single variable. However, one of the advantages that lists provide us with is the fact that we can modify their data at will.
This means that if we want to add a new element to the list, this is possible by using a method, as well as modifying, searching for an element in the list and even deleting.
This is why, in the following article, we provide a specific view on lists and how we can easily control the data within them. Having said that
Let's get started!
How to Access Items on Lists
Shoutout to Dataquest
The most basic operation we can perform with a list is to access a specific position to view the items.
You see, lists are iterable and ordered datatypes, which means that their elements will always maintain an order, being categorized by indexes, which are the specific position where they are located within the list. If we look at the following:
thislist = ["apple", "banana", "cherry"]
Immediately, apple would become index 0, banana index 1 and cherry index 2. Now, how can we access a particular index within a list?
This is easily done by placing some square brackets and indicating the index number:
print(thislist[1])
>>> 'banana
Note: What print does is to show on the screen what we place inside the brackets.
Now, what happens if we want to select more than a single element inside the list? For this, we use a range of indexes. Let's say in the following list, we want to select all ice cream flavors except for chocolate and vanilla.
icecream_flavor = ['chocolate','vanilla','pineapple','strawberry','grape'].
For this, inside the square brackets we use: which gives us a range. The number we place on the left will be the index from which we will start iterating and the number we place on the right will be the index where it will end. Seeing this:
print(icecream_flavor[2:5])
>>>['pineapple','strawberry','grape']]
Note: By default when using a range of indexes, the number to the left of [:] will be the first position (0) and the one to the right will be the last index.
So, if we want all the indexes from a specific position to the last one we would only place list[position:] and if we want to go from the first one to a specific index list[:position].
If we wanted to, we can even access the elements of the list by means of inverse indexes. What this will do is that it will start counting from the last element to the first. For example, for our ice cream flavors:
icecream_flavors = ['chocolate','vanilla','pineapple','strawberry','grape']]
print(icecream_flavors[-1])
>>> grape
How to Change Items on Lists
Shoutout to Enterprise DNA Blogs
To modify the values of the elements within a list, this will be done by accessing indexes ([]).
Thus, we only have to access the specific index of the element we want to change and then place the value we want:
list_elements = ['element1', 'element2', 'element3']
list_elements[1] = 'new_element'
print(list_elements)
>>> ['element1','new_element','element3']
As simple as this. If we would like to modify more than one element, we just use the index range and place a number of values equivalent to what we want to change.
list_elements[0:2] = ['new_element1', 'new_element2']
print(list_elements)
>>>['new_element1', 'new_element2', 'element3']
Note: We place [0:2] because at index 2 it would stop and record nothing.
How to Add Elements to Lists
Shoutout to Software Testing Help
To add elements to a list, we will use the following methods, which we will use depending on the position and type of data to be entered:
- append
- insert
- extend
append is one of the most common methods, since what it does is that it introduces a new element at the end of the list. As an example of this:
list_santa = ['bike','dolls','football']
list_santa.append('racecar')
print(list_santa)
>>> ['bike','dolls','football', 'racecar']
insert is used in those cases where we want to insert a new element in a specific position, changing the order of the other elements. Let's say that to the list of santa we want to add 'piano' in the second position [index 1]:
list_santa.insert(1, 'piano')
print(list_santa)
>>>['bike','piano','dolls','football','racecar']]
With only placing as parameters the index (1) and the value that we want to add, that element is created in the position 1. Now dolls, football and racecar are displaced in 1 and become the indexes 2,3 and 4.
If we want to add iterable elements like other lists and tuples, we use extend. Let's say we have another list with the gifts for the bad kids:
bad_list = ['coal','coal','coal']
If we want to add this to our original list, we use extend. Like this:
list_santa.extend(bad_list)
print(list_santa)
>>>['bike','piano','dolls','football', 'racecar','coal','coal','coal','coal']]
How to Remove Elements from Lists
Shoutout to Tutorial Gateway
To delete in a list, everything will depend on whether we want to delete a specific item or everything in the list:
- remove, to remove an item we know by value.
- pop, to delete an element according to its index.
- clear, to empty the list completely.
We can even delete the entire list using the del keyword, which will make the program not recognize it as a variable since it would no longer exist.
So, if we have the following list:
US_cities = ['Chicago','New York','Georgia','Detroit','San Francisco']
If we want to remove Detroit, we will only have to use remove, placing the name of the city.
US_cities.remove('Detroit')
print(US_cities)
>>> ['Chicago','New York','Georgia','San Francisco']
If we want to delete it using its index, then we use pop, noting that the index is 3:
US_cities.pop(3)
print(US_cities)
>>> ['Chicago','New York','Georgia','San Francisco']
Now, if we want to clear all the elements in the list, we just use clear.
US_cities.clear()
print(US_cities)
>>>[]
And if we want to go one step further and clear the entire list, with del we will have that if we use print we will get the following message:
of the US_cities
print(US_cities)
>>> NameError: name 'US_cities' is not defined
This is because our list will no longer exist.
You will notice that the handling of lists is totally simple, only requiring knowledge of the concepts of indexes and the methods to be used.
This way, you will be able to control the lists as you want and be an expert in the handling of iterables. This, linked to the knowledge of cycles, will prove to be of vital importance when handling a large number of values and performing different operations.
post.append(upvote)
Shoutout to Python in Plain English
En este artículo encontrarás
- Introducción
- Como acceder elementos en listas
- Como cambiar elementos en listas
- Como añadir elementos a listas
- Como remover elementos de listas
En un artículo anterior, hablé de las listas y otros tipos de DataTypes que nos permiten almacenar gran cantidad de datos en una sola variable. Sin embargo, una de las ventajas que nos proporcionan las listas es el hecho de que podemos modificar sus datos a voluntad.
Esto significa que si queremos añadir un nuevo elemento a la lista, esto es posible por medio del uso de un método, al igual que modificar, buscar un elemento en la lista e incluso eliminar.
Es por esto, que en el siguiente artículo se brinda una visión específica sobre las listas y como podemos controlar los datos dentro de estas con total facilidad. Dicho esto.
Como acceder elementos en listas
Shoutout to Dataquest
La operación más básica que podemos llevar a cabo con una lista es acceder a una posición específica para ver los elementos.
Verás, las listas son datatypes iterables y ordenadas, lo que significa que sus elementos siempre mantendrán un orden, siendo categorizados por índices, que son la posición específica donde se encuentran dentro de la lista. Si observamos la siguiente:
thislist = ["apple", "banana", "cherry"]
Inmediatamente, apple pasaría a ser el índice 0,banana el índice 1 y cherry el índice 2. Ahora bien, ¿Como podemos acceder a un índice particular dentro de una lista?
Esto se realiza facilmente colocando unas square brackets e indicando el número del índice:
print(thislist[1])
>>> 'banana'
Nota: Lo que hace print es mostrar en la pantalla lo que coloquemos dentro de los paréntesis.
¿Ahora bien, que pasa si queremos seleccionar más de un solo elemento dentro de la lista? Para esto, usamos un rango de índices. Digamos que en la siguiente lista, queremos seleccionar todos los sabores de helado excepto por chocolate y vainilla.
icecream_flavor = ['chocolate','vanilla','pineapple','strawberry','grape']
Para esto, dentro de los square brackets usamos : lo que nos da un rango. El número que coloquemos a la izquierda será el índice desde el cual empezaremos a iterar y el que coloquemos a la derecha será el índice donde terminará. Viendo esto:
print(icecream_flavor[2:5])
>>>['pineapple','strawberry','grape']
Nota: Por defecto al usar un rango de índices, tendremos que el número a la izquierda de [:] será la primera posición (0) y el que esté a la derecha el último índice.
Así, si queremos todos los índices de una posición específica hasta el último solo colocaríamos list[position:] y si queremos ir del primero hasta un índice determinado list[:position]
Si quisieramos, incluso podemos acceder a los elementos de la lista por medio de índices inversos. Lo que hara esto es que empezará a contar desde el último elemento hasta el primero. Por ejemplo, para nuestros sabores de helado:
icecream_flavors = ['chocolate','vanilla','pineapple','strawberry','grape']
print(icecream_flavors[-1])
>>> grape
Como Cambiar Elementos en Listas
Shoutout to Enterprise DNA Blogs
Para modificar los valores de los elementos dentro de una lista, esto se realizará por medio del acceso a índices ([])
Así, solo tenemos que acceder al índice específico del elemento que queremos cambiar y luego colocar el valor que deseamos:
list_elements = ['element1', 'element2', 'element3']
list_elements[1] = 'new_element'
print(list_elements)
>>> ['element1','new_element','element3']
Tan simple como esto. Si quisieramos modificar más de un elemento, solo usamos el rango de índices y colocamos una cantidad de valores equivalentes a lo que queremos cambiar.
list_elements[0:2] = ['new_element1', 'new_element2']
print(list_elements)
>>>['new_element1', 'new_element2', 'element3']
Nota: Colocamos [0:2] ya que en el índice 2 se detendría y grabaría nada.
Como Añadir Elementos a una Lista
Shoutout to Software Testing Help
Para añadir elementos a una lista, nos valdremos de los siguientes métodos, los cuales usaremos dependiendo de la posición y el tipo de datos a introducir:
- append
- insert
- extend
append es una de los métodos más comunes, ya que lo que hace es que introduce un nuevo elemento al final de la lista. Como ejemplo de esto:
list_santa = ['bike','dolls','football']
list_santa.append('racecar')
print(list_santa)
>>> ['bike','dolls','football', 'racecar']
insert se usa en aquellos casos donde queremos introducir un nuevo elemento en una posición específica, cambiando el orden de los otros elementos. Digamos a que a la lista de santa queremos agregar 'piano' en la segunda posición [índice 1]:
list_santa.insert(1, 'piano')
print(list_santa)
>>> ['bike','piano','dolls','football', 'racecar']
Con solo colocar como parámetros el índice (1) y el valor que queremos agregar, se crea ese elemento en la posición 1. Ahora dolls, football y racecar se desplazan en 1 y pasan a ser los índices 2,3 y 4.
Si queremos agregar elementos iterables como otras listas y tuplas, usamos extend. Digamos que tenemos otra lista con los regalos para los niños malos:
bad_list = ['coal','coal','coal']
Si queremos agregar esto a nuestra lista original, usamos extend. Así:
list_santa.extend(bad_list)
print(list_santa)
>>>['bike','piano','dolls','football', 'racecar','coal','coal','coal']
Como borrar elementos en una lista
Shoutout to Tutorial Gateway
Para borrar en una lista, todo dependerá de si queremos eliminar un elemento específico o todo lo que está dentro de la lista:
- remove, para eliminar un elemento que conozcamos por el valor.
- pop, para borrar un elemento de acuerdo a su índice.
- clear, para vaciar la lista completamente.
Incluso podemos eliminar la lista por completa usando la palabra clave del, lo que hará que el programa no la reconozca como variable puesto que ya no existiría.
Así, si tenemos la siguiente lista:
US_cities = ['Chicago','New York','Georgia','Detroit','San Francisco']
Si queremos eliminar Detroit, solo tendremos que usar remove, colocando el nombre de la ciudad.
US_cities.remove('Detroit')
print(US_cities)
>>> ['Chicago','New York','Georgia','San Francisco']
Si queremos borrarlo usando su índice, entonces usamos pop, notando que el índice es 3:
US_cities.pop(3)
print(US_cities)
>>> ['Chicago','New York','Georgia','San Francisco']
Ahora, si queremos borrar todos los elementos de la lista, solo usamos clear.
US_cities.clear()
print(US_cities)
>>>[]
Y si queremos ir un paso más adelante y borrar la lista por completa, con del tendremos que si usamos print nos saltará el siguiente mensaje:
del US_cities
print(US_cities)
>>> NameError: name 'US_cities' is not defined
Esto es porque nuestra lista ya no existirá.
Podrás notar que el manejo de listas es totalmente sencillo, solo requiriendo del conocimiento de los conceptos de índices y los métodos a usar.
De esta forma, ya podrás controlar las listas como quieras y ser un experto en el manejo de iterables. Esto, ligado al conocimiento de ciclos, probará ser de vital importancia a la hora de manejar gran cantidad de valores y realizar distintas operaciones.
Congratulations @jesalmofficial! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)
Your next target is to reach 4750 upvotes.
You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word
STOP
Check out our last posts:
Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!
Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).
You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.