Colecciones Python
Colecciones Python
1 - Tipos de colecciones
1.1 – Listas
Admiten elementos repetidos, respetan el orden, y son mutables. Se inicializan con corchetes.
print(thislist[1])
print(thislist[-1])
print(thislist[2:5]) #desde el elemento de índice 2 al 5 (excl.)
thislist[2] = "orange" #modificar un elemento de una posición
thislist.append("caqui")
- Unión con otra listas (o cualquier iterable) con extend()
#usando índices
for i in range(len(thislist)):
thislist[i] = thislist[i].upper()
#con while
while i < len(thislist):
print(thislist[i])
i = i + 1
1.2 – Tuplas
Las tuplas son listas ordenadas, pero INMUTABLES. No tienen la función append() o remove().
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Para hacer cambios, podemos crear una lista a partir de una tupla, modificarla, y crear una
tupla de la lista modificada.
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
print(green)
print(yellow)
print(red) # mostrará ["cherry", "strawberry", "raspberry"]
1.3 – Sets
Los sets son conjuntos de valores SIN DUPLICADOS y desordenados (el orden es aleatorio) =>
No se puede acceder por índice a los elementos ni se pueden modificar sus elementos, pero sí
borrar o añadir nuevos.
- Borramos con remove() (que lanza error si el elemento no existe) o con discard() (que no
lanza error), o con pop() (que borra un elemento aleatorio). clear() vacía el set.
thisset.remove("banana")
thisset.discard("banana")
thisset.pop()
thisset.clear()#se puede referenciar, pero estará vacío
del thisset # ya no se puede referenciar
- Combinando conjuntos
- The union() and update() y el operador | joins all items from both sets.
- The intersection() method keeps ONLY the duplicates.
- The difference() method keeps the items from the first set that are not in the other
set(s).
- The symmetric_difference() method keeps all items EXCEPT the duplicates.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
#también con get
print(thisdict.get("brand"))
- La función keys() devuelve una lista observable (dict_keys) de todas las claves
x = thisdict.keys()
x = thisdict.values()
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car["color"] = "white"
#también con update()
car.update({"color": "red"})
- Podemos obtener un dict_items (una especie de lista observable) de sus elementos que es
una lista de tuplas, cada tupla con el par (clave,valor), con la función items()
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
thisdict.popitem() #borra la clave year
- Recorridos
mydict = thisdict.copy()
mydict = dict(thisdict)
- Diccionarios anidados
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily["child2"]["name"])
2 – Condicionales
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
#operadores
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
if a > b or a > c:
print("At least one of the conditions is True")
if not a > b:
print("a is NOT greater than b")
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
4 – Bucle for
for x in range(6):
print(x)