Giampaolo Levorato
Giampaolo Levorato

Reputation: 1612

Extend lists in python

I have two lists:

x = [0,2]
y = [['1','2','1'],['5','5','5','2','1']]

I initialize a new list which should contain two lists:

z = []

I would like list "z" to look like this:

[[0,1,2],[2,3,4,5,6]]

As you can see, both lists inside list "z" has as many 1-incremental elements as the number of elements in list "y". Let me try and be more clear:

  1. you take the first element of list "x", which is 0;

  2. I want to increment that value of 0 by 1, by as many elements as is the number of elements in the first occurrence of list "y": in this example, the first occurrence of list "y" has 3 occurrences, so I'd like to get: [0,1,2]

  3. you take the second element of list "x", which is 2;

  4. I want to increment that value of 2 by 1, by as many elements as is the number of elements in the second occurrence of list "y": in this example, the second occurrence of list "y" has 5 occurrences, so I'd like to get: [2,3,4,5,6]

  5. Then I want to combine the two lists into one list called "z", such that "z" looks like this:

    [[0,1,2],[2,3,4,5,6]]

Does the question make sense?

I have tried this code:

x = [0,2]
y = [['1','2','1'],['5','5','5','2','1']]
z = []


l = []
for i in range(len(y)):
    z.append(l)
    for j in range(len(y[i])):
        print(j)
        l.append(x[i]+j)


print(z)    

But I get this result:

[[0, 1, 2, 2, 3, 4, 5, 6], [0, 1, 2, 2, 3, 4, 5, 6]]

Can anyone help me, please?

Upvotes: 2

Views: 72

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51643

Do not reuse l:

for i in range(len(y)):
    l = []                     # moved inside so its a fresh l
    z.append(l)                # and not the same l-reference
    for j in range(len(y[i])): # reused
        print(j)
        l.append(x[i]+j)

This can be achieved using enumerating over x and some indexing into y:

x = [0,2]
y = [['1','2','1'],['5','5','5','2','1']]

z = [list(range(k, k + len(y[idx]))) for idx, k in enumerate(x)]

print(z)

Output:

[[0, 1, 2], [2, 3, 4, 5, 6]]

which is equivalent to

x = [0,2]
y = [['1','2','1'],['5','5','5','2','1']]
z = []

for idx,value in enumerate(x):
    z.append( list(range(value, value + len(y[idx]))))

print(z)   

Upvotes: 3

Related Questions