-1

I am still confused those sentence after I run them, I mean how do they execute step by step, someone can give some suggestions?

print([j for i in range (10) for j in range (5)])
print([[j for i in range (10)] for j in range (5)])
print([j for i in range (10) for j in range (5) for k in range(3)])
4daJKong
  • 1,825
  • 9
  • 21

1 Answers1

2

Largely, list comprehensions are concise for loops. Sometimes they can be difficult to understand and for that reason, I would suggest converting the list comprehension into a for loop for understanding.

print([j for i in range(10) for j in range(5)])

Is the same as:

result = []
for i in range(10):
    for j in range(5):
        result.append(j)

The others are very similar, can you try and convert them to for loops?

Hint (2): The second one has a nested list, so you'll need to initialize another list and append that list to the main list, result.

Hint (3): The last list comprehension has another nested for loop with another variable k.

gmdev
  • 2,725
  • 2
  • 13
  • 28