campanella
campanella

Reputation: 31

Converting for-loop into List

i was working on this program:

  for n in range (0,31):
      if n%2 is 0:
          if (n%2)is 0 and (n%5)is 0:
              print(n)

i want the output to be like this, in list.

[0,10,20,30]

i tried to add list.append,

hehe = []

    for n in range (0,31):
        if n%2 is 0:
            if (n%2)is 0 and (n%5)is 0:
                hehe.append(n)
                print(hehe)

but the result is like this.

[0]
[0, 10]
[0, 10, 20]
[0, 10, 20, 30]

how do i make it into [0,10,20,30] only?

Thanks in advance.

Upvotes: 0

Views: 51

Answers (4)

Alec
Alec

Reputation: 9575

Because print(hehe) is inside the for loop, it is printed every time the loop is called.

Simply call it outside the loop to print it only after hehe is finished being formed.

Note that

[x for x in range(31) if not i % 10]  # anything divisible by 2 and 5 is also divisible by 10

is much cleaner and produces the same result as your for loop.

Upvotes: 1

Waket Zheng
Waket Zheng

Reputation: 6381

hehe = [i for i in range(31) if i%2 == 0 and i%5 == 0]

or

hehe = [i for i in range(31) if i % 10 == 0]

Upvotes: 0

tzaman
tzaman

Reputation: 47860

Since your print is inside the loop, it's printing it out every iteration. You want to move the print statement to the end. Also, your first if statement is redundant since you're doing the same check again in the second one, so you can remove it:

hehe = []
for n in range(0,31):
    if (n%2)==0 and (n%5)==0:
        hehe.append(n)
print(hehe)

Finally, this kind of loop is an ideal candidate for a list comprehension:

hehe = [n for n in range(0, 31) if (n%2)==0 and (n%5)==0]
print(hehe)

Also note that you should check values against 0 using == instead of is, since it's a numeric comparison.

Upvotes: 1

Alex Foster
Alex Foster

Reputation: 124

It's a formatting issue. It should be like this:

hehe = []

for n in range (0,31):
    if n%2 is 0:
        if (n%2)is 0 and (n%5)is 0:
            hehe.append(n)
print(hehe)

You need to put the print statement outside the for-loop, so it doesn't get called every time you add data to hehe.

Upvotes: 0

Related Questions