Advanced List Functions
#If you multiply a list by an integer it will repeat that list that many times
l = [1,2,3,4]
print(l*2)
List Comprehension¶
List comprehension is a way to apply some sort of logic to all values in a list. For example, if you wanted to multiply all values in a list by 2, this could be achieved with list comprehension. The format of it is that given a list l, you call it like [f(x) for x in l] where f(x) is whatever function you want to apply. In this case, if we wanted to take all values and multiply them by 2, we would say [x*2 for x in l].
#Create and print the basic list
l= [1,2,3,4]
print(l)
#Use list comprehension to multiply all values by 2
l = [x*2 for x in l]
print(l)
Modulo Function¶
The modulo function is of the form a%b and returns the remainder if you had divided the number a by b.
#The modulo operator returns the remainder of the left number divided by the right number
print(4%3)
print(7%4)
Example: Combining the Modulo Function and List Comprehension¶
Let's use both of the things we learned and find the remainder for the numbers 1 through 8 divided by 3.
#Example: Getting the remainder of all numbers in a list divided by 3
l = [1,2,3,4,5,6,7,8]
print([y%3 for y in l])
We are able to combine an if statement in the list comprehension if we want. The format is:
[f(x) for x in l if condition]
The following code below will return the numbers times 2, but only if the number (before multiplication) is greater than 2.
#Filter the list to be only values above 2 and then multiply each number by two
l = [1,2,3,4]
print(l)
l = [x*2 for x in l if x > 2]
print(l)
The Zip Function¶
The zip function takes two lists and iterates through both lists at the same time where the the elements at index 0 in the first and second list are taken, then the elements at index 1, etc.
The format for using the zip function with list comprehension is:
[f(x, y) for x, y in zip(l1, l2)]
The code below shows an example.
#Zip is the way to go through two lists together
l1 = [1,2,3,4,5]
l2 = [10,100,1000,100,10]
print([x*y for x,y in zip(l1,l2)])
Nested Lists¶
We can nest lists within lists. In the code below we create a nested list which means that the elements in the list are also lists!
#Many times we use a nested list to represent things
l = [[1,2],[3,4]]
print(l)
If we grab the first element of the list, we will have a list.
#The first index returns the first list
print(l[0])
We can index a second time to get the value in the list that was nested in the first index.
#This returns the first element of the first list element
print(l[0][0])
If we wanted the second element in the second list, we would use [1][1].
#This returns the second element of the second list element
print(l[1][1])