Python collection types and operations#

Note
These notes have been adapted from https://www.learnpython.org/ with very few modifications.
Overview#
Loops
List comprehensions
Generators
Lambdas
Dictionaries
Loops#
There are two types of loops in Python, for and while.
The for loop#
For loops iterate over a given sequence, or iterator. Here is an example:
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
For loops can iterate over a sequence of numbers using the range function. range
returns an iterator object which can be looped using the following syntax:
# Prints out the numbers 0,1,2,3,4
for x in range(5):
print(x)
# Prints out 3,4,5
for x in range(3, 6):
print(x)
# Prints out 3,5,7
for x in range(3, 8, 2):
print(x)
break and continue statements#
break is used to exit a for loop or a while loop, whereas continue is used to skip the
current block, and return to the “for” or “while” statement. A few examples:
# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)
# Prints out 0,1,2,3,4
count = 0
while True: # we have while loops in Python too.
print(count)
count += 1
if count >= 5:
break
List Comprehensions#
List Comprehensions is a very powerful tool, which creates a new list based on another list, in a single, readable line.
For example, let’s say we need to create a list of integers which specify the length of each word in a certain sentence, but only if the word is not the word “the”.
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_lengths = []
for word in words:
if word != "the":
word_lengths.append(len(word))
print(words)
print(word_lengths)
Using a list comprehension, we could simplify this process to this notation:
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_lengths = [len(word) for word in words if word != "the"]
print(words)
print(word_lengths)
Generators#
Generators are very easy to implement, but a bit difficult to understand.
Generators are used to create iterators, but with a different approach. Generators are simple functions which return an iterable set of items, one at a time, in a special way.
When an iteration over a set of item starts using the for statement, the generator is run. Once the generator’s function code reaches a “yield” statement, the generator yields its execution back to the for loop, returning a new value from the set. The generator function can generate as many values (possibly infinite) as it wants, yielding each one in its turn.
Here is a simple example of a generator function which returns 7 random integers:
import random
def lottery():
# returns 6 numbers between 1 and 40
for i in range(6):
yield random.randint(1, 40)
# returns a 7th number between 1 and 15
yield random.randint(1, 15)
for random_number in lottery():
print("And the next number is... %d!" % (random_number))
This function decides how to generate the random numbers on its own, and executes the yield statements one at a time, pausing in between to yield execution back to the main for loop.
Lambda functions#
Normally we define a function using the def keyword somewhere in the code and call it whenever we need to use it.
def sum(a, b):
return a + b
a = 1
b = 2
c = sum(a, b)
print(c)
Now instead of defining the function somewhere and calling it, we can use python’s lambda functions, which are inline functions defined at the same place we use it. So we don’t need to declare a function somewhere and revisit the code just for a single time use.
They don’t need to have a name, so they also called anonymous functions. We define a lambda function using the keyword lambda.
your_function_name = lambda inputs: output
So the above sum example using lambda function would be,
a = 1
b = 2
sum = lambda x, y: x + y
c = sum(a, b)
print(c)
Here we are assigning the lambda function to the variable sum, and upon giving the arguments i.e. a and b, it works like a normal function.
Dictionaries#
A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index to address it.
For example, a database of phone numbers could be stored using a dictionary like this:
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(phonebook)
Alternatively, a dictionary can be initialized with the same values in the following notation:
phonebook = {"John": 938477566, "Jack": 938377264, "Jill": 947662781}
print(phonebook)
Iterating over dictionaries#
Dictionaries can be iterated over, just like a list. However, a dictionary, unlike a list, does not keep the order of the values stored in it. To iterate over key value pairs, use the following syntax:
phonebook = {"John": 938477566, "Jack": 938377264, "Jill": 947662781}
for name, number in phonebook.items():
print("Phone number of %s is %d" % (name, number))
Removing a value#
To remove a specified index, use either one of the following notations:
phonebook = {"John": 938477566, "Jack": 938377264, "Jill": 947662781}
del phonebook["John"]
print(phonebook)
or:
phonebook = {"John": 938477566, "Jack": 938377264, "Jill": 947662781}
phonebook.pop("John")
print(phonebook)