PROGRAMMING

  minte9
learningjourney




S R Q

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    
Last update: 90 days ago
Generator