Loops (while and for)

Loops (while and for)#

  • Blocks while and for

  • Keywords in, break and continue

for idx in range(4):
    print(idx, end=", ")
0, 1, 2, 3, 

list: list comprehension#

They are iterable so they are often used to make loops. We have already seen how to use the keyword for. For example to build a new list (side note: x**2 computes x^2):

l0 = [1, 4, 10]
l1 = []
for number in l0:
    l1.append(number**2)

print(l1)
[1, 16, 100]

There is a more readable (and slightly more efficient) method to do such things, the list comprehension:

l1 = [number**2 for number in l0]
print(l1)
[1, 16, 100]
# list comprehension with a condition
[s for s in ["a", "bbb", "e"] if len(s) == 1]
['a', 'e']
# lists comprehensions can be cascaded
[(x, y) for x in [1, 2] for y in ["a", "b"]]
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

Exercise 5 (advanced)

  • Write a function extract_patterns(text, n=3) extracting the list of patterns of size n=3 from a long string (e.g. if text = "basically", patterns would be the list ['bas', 'asi', 'sic', ..., 'lly']). Use list comprehension, range, slicing. Use a sliding window.

  • You can apply your function to a long “ipsum lorem” string (ask to your favorite web search engine).