Link_tester
Link_tester

Reputation: 1081

How to split a list created through several iterations of a for loop in python

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.

Upvotes: 0

Views: 1246

Answers (4)

tbjorch
tbjorch

Reputation: 1748

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]]

Upvotes: 2

Zeinab Mardi
Zeinab Mardi

Reputation: 131

a = [[i for i in range(0,10,2)]]*2
print(a)
[[0, 2, 4, 6, 8], [0, 2, 4, 6, 8]]

Upvotes: 1

Amir Bahrami
Amir Bahrami

Reputation: 53

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)))

Upvotes: 1

Yehla
Yehla

Reputation: 191

How about this?

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

Upvotes: 1

Related Questions