Loops (while and for)#
Blocks
whileandforKeywords
in,breakandcontinue
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 sizen=3from a long string (e.g. iftext = "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).
Solution to Exercise 5 (advanced)
text = "basically"
def extract_patterns(text, n=3):
pat = [text[i : i + n] for i in range(len(text) - n + 1)]
return pat
print("patterns=", extract_patterns(text))
print("patterns=", extract_patterns(text, n=5))
patterns= ['bas', 'asi', 'sic', 'ica', 'cal', 'all', 'lly']
patterns= ['basic', 'asica', 'sical', 'icall', 'cally']