Cheatsheets / flujo, datos e iteración
Listas de Python
Liza
En Python, las listas son colecciones ordenadas de
elementos que permiten un uso sencillo de un conjunto primes = [2, 3, 5, 7, 11]
de datos. print(primes)
Los valores de lista se colocan entre corchetes [ ] ,
separados por comas. Es una buena práctica poner un empty_list = []
espacio entre la coma y el siguiente valor. No es
necesario que los valores de una lista sean únicos (se
puede repetir el mismo valor).
Las listas vacías no contienen ningún valor entre
corchetes.
Sumar listas juntas
En Python, las listas se pueden agregar entre sí usando
el símbolo más + . Como se muestra en el bloque de items = ['cake', 'cookie', 'bread']
código, esto dará como resultado una nueva lista que total_items = items + ['biscuit', 'tart']
contiene los mismos elementos en el mismo orden con print(total_items)
los elementos de la primera lista en primer lugar. # Result: ['cake', 'cookie', 'bread',
Note: This will not work for adding one item at a time 'biscuit', 'tart']
(use .append() method). In order to add one item,
create a new list with a single value and then use the
plus symbol to add the list.
Python Lists: Data Types
In Python, lists are a versatile data type that can contain
multiple different data types within the same square numbers = [1, 2, 3, 4, 10]
brackets. The possible data types within a list include names = ['Jenny', 'Sam', 'Alexis']
numbers, strings, other objects, and even other lists. mixed = ['Jenny', 1, 2]
list_of_lists = [['a', 1], ['b', 2]]
List Method .append()
In Python, you can add values to the end of a list using
the .append() method. This will place the object orders = ['daisies', 'periwinkle']
passed in as a new element at the very end of the list. orders.append('tulips')
Printing the list afterwards will visually show the print(orders)
appended value. This .append() method is not to # Result: ['daisies', 'periwinkle',
be confused with returning an entirely new list with the 'tulips']
passed object.
/
Aggregating Iterables Using zip()
In Python, data types that can be iterated (called
iterables) can be used with the zip() function to owners_names = ['Jenny', 'Sam', 'Alexis']
aggregate data. The zip() function takes iterables, dogs_names = ['Elphonse', 'Dr. Doggy DDS',
aggregates corresponding elements based on the 'Carter']
iterables passed in, and returns an iterator. Each element owners_dogs = zip(owners_names,
of the returned iterator is a tuple of values. dogs_names)
As shown in the example, zip() is aggregating the print(list(owners_dogs))
data between the owners’ names and the dogs’ names # Result: [('Jenny', 'Elphonse'), ('Sam',
to match the owner to their dogs. zip() returns an 'Dr.Doggy DDS'), ('Alexis', 'Carter')]
iterator containing the data based on what the user
passes to the function. Empty iterables passed in will
result in an empty iterator. To view the contents of the
iterator returned from zip() , we can cast it as a list
by using the list() function and printing the results.
List Item Ranges Including First or Last Item
In Python, when selecting a range of list items, if the first
item to be selected is at index 0 , no index needs to be items = [1, 2, 3, 4, 5, 6]
specified before the : . Similarly, if the last item
selected is the last item in the list, no index needs to be # All items from index `0` to `3`
specified after the : . print(items[:4])
# All items from index `2` to the last
item, inclusive
print(items[2:])
List Method .count()
The .count() Python list method searches a list for
whatever search term it receives as an argument, then backpack = ['pencil', 'pen', 'notebook',
returns the number of matching entries found. 'textbook', 'pen', 'highlighter', 'pen']
numPen = backpack.count('pen')
print(numPen)
# Output: 3
Determining List Length with len()
The Python len() function can be used to determine
the number of items found in the list it accepts as an knapsack = [2, 4, 3, 7, 10]
argument. size = len(knapsack)
print(size)
# Output: 5
/
Zero-Indexing
In Python, list index begins at zero and ends at the
length of the list minus one. For example, in this list, names = ['Roger', 'Rafael', 'Andy',
'Andy' is found at index 2 . 'Novak']
List Method .sort()
The .sort() Python list method will sort the
contents of whatever list it is called on. Numerical lists exampleList = [4, 2, 1, 3]
will be sorted in ascending order, and lists of Strings will exampleList.sort()
be sorted into alphabetical order. It modifies the original print(exampleList)
list, and has no return value. # Output: [1, 2, 3, 4]
List Indices
Python list elements are ordered by index, a number
referring to their placement in the list. List indices start at berries = ["blueberry", "cranberry",
0 and increment by one. "raspberry"]
To access a list element by index, square bracket
notation is used: list[index] . berries[0] # "blueberry"
berries[2] # "raspberry"
Negative List Indices
Negative indices for lists in Python can be used to
reference elements in relation to the end of a list. This soups = ['minestrone', 'lentil', 'pho',
can be used to access single list elements or as part of 'laksa']
defining a list range. For instance: soups[-1] # 'laksa'
soups[-3:] # 'lentil', 'pho', 'laksa'
●
To select the last element, my_list[-1] .
soups[:-2] # 'minestrone', 'lentil'
● To select the last three elements,
my_list[-3:] .
● To select everything except the last two elements,
my_list[:-2] .
List Slicing
A slice, or sub-list of Python list elements can be
selected from a list using a colon-separated starting and tools = ['pen', 'hammer', 'lever']
ending point. tools_slice = tools[1:3] # ['hammer',
The syntax pattern is 'lever']
myList[START_NUMBER:END_NUMBER] . The tools_slice[0] = 'nail'
slice will include the START_NUMBER index, and
everything until but excluding the END_NUMBER item. # Original list is unaltered:
When slicing a list, a new list is returned, so if the slice is print(tools) # ['pen', 'hammer', 'lever']
saved and then altered, the original list remains the
same.
/
sorted() Function
The Python sorted() function accepts a list as an
argument, and will return a new, sorted list containing unsortedList = [4, 2, 1, 3]
the same elements as the original. Numerical lists will be sortedList = sorted(unsortedList)
sorted in ascending order, and lists of Strings will be print(sortedList)
sorted into alphabetical order. It does not modify the # Output: [1, 2, 3, 4]
original, unsorted list.