Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Indexación: nombre[indice]
>>> L[0] #0 es el primer índice (en Matlab es 1)
20
>>> L[1]
30
>>> L[2]
10
>>> L=[20,30,10]
Concatenación
>>> L+L
[20, 30, 10, 20, 30, 10]
>>> L*2
[20, 30, 10, 20, 30, 10]
Comparación
>>> L>[2,4,6] #compara elemento a elemento
True
Sublista (slice)
>>> L[1:3] #lista c/valores entre indices 1 y 2 (3-1)
[30, 10]
“Aliasing”
>>> L=[20,30,10]
[20, 30, 10]
>>> M=L #M es un alias de L
>>> M
[20, 30, 10]
>>> M[0]=200
>>> M
[200, 30, 10]
>>> L
[200, 30, 10]
>>>
Instrucción for
Ejemplo
>>> L=[20,30,10]
>>> for valor in L:
print valor
20
30
10
Sintaxis
for variable in lista: instrucciones
Semántica
•La variable toma consecutivamente todos los valores de la lista.
•Para cada valor ejecuta las instrucciones
Funciones para listas
def suma(lista):
assert type(lista)==list
s=0
for numero in lista:
s = s + numero
return s
assert suma([20,30,10])==60
Notas
lista se considera un alias del argumento
si se modifica parámetro lista dentro de la función afecta a
argumento en la invocación
Funciones predefinidas para listas
Ejemplos:
Uso habitual:
for i in range(n): instrucciones
en cada iteración, i toma un valor de la lista [0,1,,…,n-1]
def indice(x,L):
assert type(L)==list
for i in range( len(L) ):
if L[i]==x: return i
return None
assert indice(30,[20,30,10])==1
assert indice(40,[20,30,10])==None
Funciones predefinidas
>>>help(list)
| append(...)
| L.append(object) -- append object to end
|
| count(...)
| L.count(value) -> integer -- return number of occurrences of value
|
| extend(...)
| L.extend(iterable) -- extend list by appending elements from the iterable
|
| index(...)
| L.index(value, [start, [stop]]) -> integer -- return first index of value.
| Raises ValueError if the value is not present.
|
Funciones predefinidas (cont…)
| insert(...)
| L.insert(index, object) -- insert object before index
|
| pop(...)
| L.pop([index]) -> item -- remove and return item at index (default last).
| Raises IndexError if list is empty or index is out of range.
|
| remove(...)
| L.remove(value) -- remove first occurrence of value.
| Raises ValueError if the value is not present.
|
| reverse(...)
| L.reverse() -- reverse *IN PLACE*
|
| sort(...)
| L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
| cmp(x, y) -> -1, 0, 1
|
Buscar, agregar, borrar cambiar
• Buscar
– operador de existencia: valor in L
– índice: L.index(valor)
• Agregar
– al final: L.append(valor)
– en índice: L.insert(i,valor) (resto “se desplaza”)
• Borrar
– valor: L.remove(valor)
– índice: valor=L.pop(i) (resto “se desplaza”)
• Cambiar
– L[i]=valor
Ejercicio
Agenda: representación list
#registro: nombre(str) fono(int)
estructura.mutable("registro","nombre fono")
#agenda: list(registro)
agenda=[registro("a",2),registro("c",1),registro("d",4)]