Listas

Python tiene un tipo de datos por listas. Las listas pueden tener strings o numeros.
Para acceder al elemento usar [].

#!/usr/bin/python
 
l = [ "Drake", "Derp", "Derek", "Dominique" ]
 
print l     # prints all elements
print l[0]  # print first element
print l[1]  # prints second element

Resultado:

['Drake', 'Derp', 'Derek', 'Dominique']
Drake
Derp

Manipular la lista
Ustedes pueden añadir elementos a listad con funcion append()
Para quitar elementos usar remover().

#!/usr/bin/python
 
l = [ "Drake", "Derp", "Derek", "Dominique" ]
 
print l                # prints all elements
l.append("Victoria")   # add element.
print l                # print all elements
l.remove("Derp")       # remove element.
l.remove("Drake")      # remove element.
print l                # print all elements.

Resultado:

['Drake', 'Derp', 'Derek', 'Dominique']
['Drake', 'Derp', 'Derek', 'Dominique', 'Victoria']
['Derek', 'Dominique', 'Victoria']

Orden de la lista
Ordenar la lista con sort()

#!/usr/bin/python
 
l = [ "Drake", "Derp", "Derek", "Dominique" ]
 
print l     # prints all elements
l.sort()    # sorts the list in alphabetical order
print l     # prints all elements

Resultado:

['Drake', 'Derp', 'Derek', 'Dominique']
['Derek', 'Derp', 'Dominique', 'Drake']

Invertir lista con reverse()

#!/usr/bin/python
 
l = [ "Drake", "Derp", "Derek", "Dominique" ]
 
print l     # prints all elements
l.sort()    # sorts the list in alphabetical order
l.reverse() # reverse order.
print l     # prints all elements

Resultado:


['Drake', 'Derp', 'Derek', 'Dominique']
['Drake', 'Dominique', 'Derp', 'Derek']

Deja un comentario