Home > Mobile >  Want to print out a list when using range
Want to print out a list when using range

Time:09-30

I am trying to take the elements that are being printed and put them into a list as the output. The output is the correct numbers but I want them in a list.

for i in range(0,10):
    calc= 0
    if i % 2 == 0:
        print(i)

CodePudding user response:

If you want to keep this form, you could append the relevant numbers to a list:

result = []
for i in range(0, 10):
    if i % 2 == 0:
        result.append(i)

But the more idiomatic approach would be to use a list comprehension:

result = [i for i in range(0, 10) if i % 2 == 0]
  • Related