28. list methods¶
The methods of lists are functions associated with lists that can be used to handle lists. They are called by adding a period and the name of the method:
>>> lista = [1, 2, 3, 4, 5]
>>> lista.append(6) # Añadir un elemento al final de la lista
>>> lista
[1, 2, 3, 4, 5, 6]
>>> lista.pop() # Retira un elemento del final de la lista
6
>>> lista
[1, 2, 3, 4, 5]
>>> lista.pop(0) # Retira un elemento del comienzo de la lista
1
>>> lista
[2, 3, 4, 5]
>>> lista.index(4) # Devuelve la posición de un elemento en la lista
2
>>> lista.count(3) # Devuelve cuántas veces encuentra 3 en la lista
1
>>> lista = ['uno', 'dos', 'tres']
>>> ', '.join(lista) # Une las cadenas de texto de una lista
'uno, dos, tres'
functions with lists¶
-
max
(lista)¶ The
max(list)
function returns the element with the greatest value of all the elements in the list:>>> max([1, 8, 5, 6, 3]) 8
-
min
(lista)¶ The
min(list)
function returns the element with the least value of all the elements in the list:>>> max(['hola', 'mundo']) 'hola'
-
sum
(lista)¶ The
sum(list)
function returns the sum of all numbers contained in a list:>>> sum([1, 8, 5, 6, 3]) 23
-
len
(lista)¶ The
len(list)
function returns the number of elements contained in a list:>>> len([1, 8, 5, 6, 3]) 5
-
sorted
(lista)¶ The
sorted(list)
function returns another list sorted from smallest to largest:>>> sorted([1, 8, 5, 6, 3]) [1, 3, 5, 6, 8]
-
list
(elementos)¶ Convert an iterable to a list:
>>> list('Hola, mundo') ['H', 'o', 'l', 'a', ',', ' ', 'm', 'u', 'n', 'd', 'o'] >>> list(range(10, -1, -2)) [10, 8, 6, 4, 2, 0]
Exercises¶
Write a function that calculates the average of a list of numbers. The average is equal to the sum of the elements divided by the number of elements.
Call the function to calculate the average of the following lists:
[10, 20, 30, 40, 50] [7.0, 5.5, 6.8, 6.3, 8.2]
Write a function that accepts a list as an argument and returns another list containing only the even numbers.
You must create a new empty list and add the even numbers from the passed list as an argument to it.
Calls the function with the following lists as arguments:
[3, 77, 78, 84, 75, 54, 8, 66, 8, 13] [81, 52, 78, 88, 51, 74, 23, 60, 47, 4]
Write a function that accepts a list as an argument and returns another list with the smallest element, the largest element, the number of elements, and the sum of all elements.
Calls the function with the following lists as argument:
>>> resumen([49, 9, 16, 31, 6, 35, 14, 7, 7, 15, 13, 44, 38, 43]) [6, 49, 14, 327] >>> resumen([28, 13, 24, 45, 48, 47, 7, 43, 5, 24]) [5, 48, 10, 284] >>> resumen([7, 32, 45, 47, 24, 10, 1, 18, 38, 36, 22, 50]) [1, 50, 12, 330]