Listas#


Las listas son tipos compuestos (pueden contener más de un valor), se definen separando los valores con comas, encerrados entre corchetes. En general las listas pueden contener diferentes tipos, y pueden no ser todos iguales, tales como: números, cadenas, booleanos, ...y tambien listas. Sin embargo, suelen utilizarse con ítems del mismo tipo para mantener un orden y por buenas prácticas de codificación.

  • Los elementos no son necesariamente homogéneos en tipo
  • Elementos ordenados
  • Acceso mediante un índice
  • Están definidas operaciones entre Listas, así como algunos métodos:
    • x in L (¿x es un elemento de L?)
    • x not in L (¿x no es un elemento de L?)
    • L1 + L2 (concatenar L1 y L2)
    • n*L1 (n veces L1)
    • L1*n (n veces L1)
    • L[i] (Elemento i-ésimo)
    • L[i:j] (Elementos i a j)
    • L[i:j:k] (Elementos i a j, elegidos uno de cada k)
    • len(L) (longitud de L)
    • min(L) (Mínimo de L)
    • max(L) (Máximo de L)
    • L.index(x) (Índice de x, iniciando en i)
    • L.count(x) (Número de veces que aparece x en L)
    • L.append(x) (Agrega el elemento x al final)

Veamos algunos ejemplos:#

Numeros_primos=[2,3,5,7,11]
2 in Numeros_primos
True
2 not in Numeros_primos
False
2*Numeros_primos
[2, 3, 5, 7, 11, 2, 3, 5, 7, 11]
Numeros_primos[0]
2
Numeros_primos[-1]

print(Numeros_primos[4])
11
Numeros_primos[0:3]
[2, 3, 5]
Numeros_primos[::2]
[2, 5, 11]
len(Numeros_primos)
5
min(Numeros_primos),max(Numeros_primos)
(2, 11)
Numeros_primos.index(11)
4

Operaciones con Listas:#

Veamos algunas operaciones que se pueden realizar sobre listas.
Por ejemplo, se puede fácilmente:

  • concatenar dos listas
  • buscar un valor dado
  • agregar elementos
  • borrar elementos
  • calcular su longitud
  • invertirla

Empecemos concatenando dos listas, usando el operador “suma”

L1=[1,2,3,4,5]
L2=[6,7,8,9,10]
L3=L1+L2
print(L3)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2*L1==L1+L1
True
L2[2] in L1
False
L2.index(6)
0
help(list)
Help on class list in module builtins:

class list(object)
 |  list(iterable=(), /)
 |  
 |  Built-in mutable sequence.
 |  
 |  If no argument is given, the constructor creates a new empty list.
 |  The argument must be an iterable if specified.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |  
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(self, /)
 |      Return a reverse iterator over the list.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __setitem__(self, key, value, /)
 |      Set self[key] to value.
 |  
 |  __sizeof__(self, /)
 |      Return the size of the list in memory, in bytes.
 |  
 |  append(self, object, /)
 |      Append object to the end of the list.
 |  
 |  clear(self, /)
 |      Remove all items from list.
 |  
 |  copy(self, /)
 |      Return a shallow copy of the list.
 |  
 |  count(self, value, /)
 |      Return number of occurrences of value.
 |  
 |  extend(self, iterable, /)
 |      Extend list by appending elements from the iterable.
 |  
 |  index(self, value, start=0, stop=9223372036854775807, /)
 |      Return first index of value.
 |      
 |      Raises ValueError if the value is not present.
 |  
 |  insert(self, index, object, /)
 |      Insert object before index.
 |  
 |  pop(self, index=-1, /)
 |      Remove and return item at index (default last).
 |      
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(self, value, /)
 |      Remove first occurrence of value.
 |      
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(self, /)
 |      Reverse *IN PLACE*.
 |  
 |  sort(self, /, *, key=None, reverse=False)
 |      Sort the list in ascending order and return None.
 |      
 |      The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
 |      order of two equal elements is maintained).
 |      
 |      If a key function is given, apply it once to each list item and sort them,
 |      ascending or descending, according to their function values.
 |      
 |      The reverse flag can be set to sort in descending order.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

Creamos una lista vacia e iremos añadiendole elementos al final con el método append()

L3=[]
L3.append([2,2])
L3
[[2, 2]]
L3.append(L1)
L3
[[2, 2], [1, 2, 3, 4, 5]]

Para añadir un elemento en una posición específica debemos usar el método insert()

L3.insert(0,11)
L3
[11, [2, 2], [1, 2, 3, 4, 5]]
L3.insert(2,L2)
L3
[11, [2, 2], [6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]

En las listas se pueden cambiar el valor de 1 o más de sus elementos

print(L3)
L3[0]=1
L3
[11, [2, 2], [6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]
[1, [2, 2], [6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]
L3[:3]=[3,4,5]
L3
[3, 4, 5, [1, 2, 3, 4, 5]]

Para eliminar un elemento de la lista, usamos el método remove()

L3.remove(3)
L3
[4, 5, [1, 2, 3, 4, 5]]

Para revertir el orden de los elementos, usamos el método reverse()

L3.reverse()
L3
[[1, 2, 3, 4, 5], 5, 4]

Complemento#

Para crear más rápido una lista con una secuencia de números, usamos el tipo de variable llamado range

  • range(fin)
  • range(inicio, fin, paso)
range(20)
range(0, 20)
list(range(20))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
range(1,30,2)
range(1, 30, 2)
list(range(1,30,2))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]

Para una lista cuyos elementos sean números, usamos el método sum() para realizar la suma de todos sus elementos

L4=[1,2,3,4,5,6,7,8,9]
sum(L4)
45
sum(list(range(1,30,2)))
225