En este artículo, aprenderemos todo sobre las listas de Python, cómo se crean, cómo dividir una lista, agregar o eliminar elementos de ellas, etc.
Vídeo: listas y tuplas de Python
Python ofrece una variedad de tipos de datos compuestos a menudo denominados secuencias. List es uno de los tipos de datos más versátiles y utilizados en Python.
¿Cómo crear una lista?
En la programación de Python, se crea una lista colocando todos los elementos (elementos) entre corchetes ()
, separados por comas.
Puede tener cualquier número de elementos y pueden ser de diferentes tipos (entero, flotante, cadena, etc.).
# empty list my_list = () # list of integers my_list = (1, 2, 3) # list with mixed data types my_list = (1, "Hello", 3.4)
Una lista también puede tener otra lista como elemento. Esto se llama lista anidada.
# nested list my_list = ("mouse", (8, 4, 6), ('a'))
¿Cómo acceder a elementos de una lista?
Hay varias formas en las que podemos acceder a los elementos de una lista.
Índice de lista
Podemos usar el operador de índice ()
para acceder a un elemento en una lista. En Python, los índices comienzan en 0. Entonces, una lista que tenga 5 elementos tendrá un índice de 0 a 4.
Intentar acceder a índices distintos de estos generará un IndexError
. El índice debe ser un número entero. No podemos usar float u otros tipos, esto dará como resultado TypeError
.
Se accede a las listas anidadas mediante la indexación anidada.
# List indexing my_list = ('p', 'r', 'o', 'b', 'e') # Output: p print(my_list(0)) # Output: o print(my_list(2)) # Output: e print(my_list(4)) # Nested List n_list = ("Happy", (2, 0, 1, 5)) # Nested indexing print(n_list(0)(1)) print(n_list(1)(3)) # Error! Only integer can be used for indexing print(my_list(4.0))
Salida
poea 5 Traceback (última llamada más reciente): Archivo "", línea 21, en TypeError: los índices de lista deben ser enteros o porciones, no flotantes
Indexación negativa
Python permite la indexación negativa de sus secuencias. El índice de -1 se refiere al último elemento, -2 al penúltimo elemento y así sucesivamente.
# Negative indexing in lists my_list = ('p','r','o','b','e') print(my_list(-1)) print(my_list(-5))
Cuando ejecutamos el programa anterior, obtendremos el siguiente resultado:
ep

¿Cómo dividir listas en Python?
Podemos acceder a un rango de elementos en una lista usando el operador de corte :
(dos puntos).
# List slicing in Python my_list = ('p','r','o','g','r','a','m','i','z') # elements 3rd to 5th print(my_list(2:5)) # elements beginning to 4th print(my_list(:-5)) # elements 6th to end print(my_list(5:)) # elements beginning to end print(my_list(:))
Salida
('o', 'g', 'r') ('p', 'r', 'o', 'g') ('a', 'm', 'i', 'z') ('p ',' r ',' o ',' g ',' r ',' a ',' m ',' i ',' z ')
El corte se puede visualizar mejor si se considera que el índice se encuentra entre los elementos, como se muestra a continuación. Entonces, si queremos acceder a un rango, necesitamos dos índices que corten esa parte de la lista.

¿Cómo cambiar o agregar elementos a una lista?
Las listas son mutables, lo que significa que sus elementos se pueden cambiar a diferencia de la cadena o la tupla.
Podemos usar el operador de asignación ( =
) para cambiar un elemento o un rango de elementos.
# Correcting mistake values in a list odd = (2, 4, 6, 8) # change the 1st item odd(0) = 1 print(odd) # change 2nd to 4th items odd(1:4) = (3, 5, 7) print(odd)
Salida
(1, 4, 6, 8) (1, 3, 5, 7)
Podemos agregar un elemento a una lista usando el append()
método o agregar varios elementos usando el extend()
método.
# Appending and Extending lists in Python odd = (1, 3, 5) odd.append(7) print(odd) odd.extend((9, 11, 13)) print(odd)
Salida
(1, 3, 5, 7) (1, 3, 5, 7, 9, 11, 13)
También podemos usar el +
operador para combinar dos listas. A esto también se le llama concatenación.
El *
operador repite una lista el número de veces especificado.
# Concatenating and repeating lists odd = (1, 3, 5) print(odd + (9, 7, 5)) print(("re") * 3)
Salida
(1, 3, 5, 9, 7, 5) ('re', 're', 're')
Además, podemos insertar un elemento en la ubicación deseada utilizando el método insert()
o insertar varios elementos comprimiéndolo en un segmento vacío de una lista.
# Demonstration of list insert() method odd = (1, 9) odd.insert(1,3) print(odd) odd(2:2) = (5, 7) print(odd)
Salida
(1, 3, 9) (1, 3, 5, 7, 9)
¿Cómo eliminar o eliminar elementos de una lista?
Podemos eliminar uno o más elementos de una lista usando la palabra clave del
. Incluso puede eliminar la lista por completo.
# Deleting list items my_list = ('p', 'r', 'o', 'b', 'l', 'e', 'm') # delete one item del my_list(2) print(my_list) # delete multiple items del my_list(1:5) print(my_list) # delete entire list del my_list # Error: List not defined print(my_list)
Salida
('p', 'r', 'b', 'l', 'e', 'm') ('p', 'm') Rastreo (última llamada más reciente): Archivo "", línea 18, en NameError: el nombre 'my_list' no está definido
Podemos usar el remove()
método para eliminar el elemento dado o el pop()
método para eliminar un elemento en el índice dado.
The pop()
method removes and returns the last item if the index is not provided. This helps us implement lists as stacks (first in, last out data structure).
We can also use the clear()
method to empty a list.
my_list = ('p','r','o','b','l','e','m') my_list.remove('p') # Output: ('r', 'o', 'b', 'l', 'e', 'm') print(my_list) # Output: 'o' print(my_list.pop(1)) # Output: ('r', 'b', 'l', 'e', 'm') print(my_list) # Output: 'm' print(my_list.pop()) # Output: ('r', 'b', 'l', 'e') print(my_list) my_list.clear() # Output: () print(my_list)
Output
('r', 'o', 'b', 'l', 'e', 'm') o ('r', 'b', 'l', 'e', 'm') m ('r', 'b', 'l', 'e') ()
Finally, we can also delete items in a list by assigning an empty list to a slice of elements.
>>> my_list = ('p','r','o','b','l','e','m') >>> my_list(2:3) = () >>> my_list ('p', 'r', 'b', 'l', 'e', 'm') >>> my_list(2:5) = () >>> my_list ('p', 'r', 'm')
Python List Methods
Methods that are available with list objects in Python programming are tabulated below.
They are accessed as list.method()
. Some of the methods have already been used above.
Python List Methods |
---|
append() - Add an element to the end of the list |
extend() - Add all elements of a list to the another list |
insert() - Insert an item at the defined index |
remove() - Removes an item from the list |
pop() - Removes and returns an element at the given index |
clear() - Removes all items from the list |
index() - Returns the index of the first matched item |
count() - Returns the count of the number of items passed as an argument |
sort() - Sort items in a list in ascending order |
reverse() - Reverse the order of items in the list |
copy() - Returns a shallow copy of the list |
Some examples of Python list methods:
# Python list methods my_list = (3, 8, 1, 6, 0, 8, 4) # Output: 1 print(my_list.index(8)) # Output: 2 print(my_list.count(8)) my_list.sort() # Output: (0, 1, 3, 4, 6, 8, 8) print(my_list) my_list.reverse() # Output: (8, 8, 6, 4, 3, 1, 0) print(my_list)
Output
1 2 (0, 1, 3, 4, 6, 8, 8) (8, 8, 6, 4, 3, 1, 0)
List Comprehension: Elegant way to create new List
List comprehension is an elegant and concise way to create a new list from an existing list in Python.
A list comprehension consists of an expression followed by for statement inside square brackets.
Here is an example to make a list with each item being increasing power of 2.
pow2 = (2 ** x for x in range(10)) print(pow2)
Output
(1, 2, 4, 8, 16, 32, 64, 128, 256, 512)
This code is equivalent to:
pow2 = () for x in range(10): pow2.append(2 ** x)
A list comprehension can optionally contain more for
or if statements. An optional if
statement can filter out items for the new list. Here are some examples.
>>> pow2 = (2 ** x for x in range(10) if x> 5) >>> pow2 (64, 128, 256, 512) >>> odd = (x for x in range(20) if x % 2 == 1) >>> odd (1, 3, 5, 7, 9, 11, 13, 15, 17, 19) >>> (x+y for x in ('Python ','C ') for y in ('Language','Programming')) ('Python Language', 'Python Programming', 'C Language', 'C Programming')
Other List Operations in Python
List Membership Test
We can test if an item exists in a list or not, using the keyword in
.
my_list = ('p', 'r', 'o', 'b', 'l', 'e', 'm') # Output: True print('p' in my_list) # Output: False print('a' in my_list) # Output: True print('c' not in my_list)
Output
True False True
Iterating Through a List
Using a for
loop we can iterate through each item in a list.
for fruit in ('apple','banana','mango'): print("I like",fruit)
Output
Me gusta la manzana me gusta el banano me gusta el mango