0

I am creating a list in a for loop in python but I have no idea how to separate results of each itertaion. For example I want to keep the even numbers from 0 to 10 two times and I want to separate the results. I tried the following code:

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

But res is

[0, 2, 4, 6, 8, 0, 2, 4, 6, 8]

And I want to have it as:

[[0, 2, 4, 6, 8], [0, 2, 4, 6, 8]]

The point is that in reality results of my iteration have not the same length and I can not simply split my res based on the number of iteration. I do appreciate if anyone help me to do it.

1
  • 1
    append new empty sublist for every i before the inner loop Commented Mar 10, 2021 at 15:03

4 Answers 4

2

You have to create a list in the first loop level which you then append to the res list to achieve that. Below is your code modified to minimum to achieve what you want.

res=[]
for i in range (2):
    temp = []
    for j in range (10):
        if j%2==0:
            temp.append(j)
    res.append(temp)

alt. use a list comprehension. Note that the range function also has a third argument allowing you to set the step size, which if set to 2 removes the need to check j%2 == 0.

[list(range(0,9,2)) for i in range(2)]

Both of these creates the list [[0, 2, 4, 6, 8], [0, 2, 4, 6, 8]]

Sign up to request clarification or add additional context in comments.

Comments

1

How about this?

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

1 Comment

This solution is only limited to a range = 2. Check @tbjorch's answer, which works for values > 2
1

Use a generator for each up itrate:

def gen(x):
    for i in range(x):
        if i % 2 == 0 :
            yield i

Then:

array = []
for i in range(2):
     array.append(list(gen(10)))

2 Comments

the gen function it not necessary since range has the step size argument. This would achieve the same: array.append(list(range(0,9,2)))
Yes, but i meant to mention a maybe new approach @tbjorch
1
a = [[i for i in range(0,10,2)]]*2
print(a)
[[0, 2, 4, 6, 8], [0, 2, 4, 6, 8]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.