PYTHON

  minte9
REMEMBERS




Loop

p329 Normal use of a for loop.
 
# Normal use of a for loop ...
#
# without list comprehension

str = "abc"
res = []

for s in str:
    res.append(s.capitalize())

assert res == ['A', 'B', 'C']

Comprehension

For loops can be write more concisely using list comprehension.
 
# List comprehension
#
# The loop variable appears in expression before we get to definition
# List comprehensions are more concise but are harder to debug

str = "abc"
res = [s.capitalize() for s in str]

assert res == ['A', 'B', 'C']

Questions     github Goodies
Generator
        A B C D E F
🔔
1/1