Karen
Karen

Reputation: 3

Python iterating a list and creating a nested list out of all iterations

I've been trying to figure out how I could code the following:

I have a list say:

L = [1, 2, 3, 4, 5]

I am trying to multiply each element in groups of 2 and so I'm expecting 4 lists at the end:

[-1, -2, 3, 4, 5]
[1, -2, -3, 4, 5]
[1, 2, -3, -4, 5]
[1, 2, 3, -4, -5]

Now with these 4 lists I intend to create a nested list again say:

M = [[-1, -2, 3, 4, 5], [1, -2, -3, 4, 5],[1, 2, -3, -4, 5], [1, 2, 3, -4, -5]]

So far I got this:

L = [1, 2, 3, 4, 5]
L2 = L.copy()
print(L)

for x in range(0,2):
    for y in range(x,2+x):
        N = []
        L2[y] = L2[y] * -1
        N.append(L2)
        print(N)

and it's showing as this

[1, 2, 3, 4, 5]
[[-1, 2, 3, 4, 5]]
[[-1, -2, 3, 4, 5]]
[[-1, 2, 3, 4, 5]]
[[-1, 2, -3, 4, 5]]

I can't generate the nested list because I don't know how to call a list whose elements have been modified from the loop I created. I am also having issues with my loop. I want it to read the old list in a fresh slate rather than referring to the altered list from the previous loop.

I'm very new to python but I am enjoying learning this new language. Often times I get stuck and easily figure out what I need to happen. This one is a bit trickier on my end so I am asking for help. Thanks!

Upvotes: 0

Views: 80

Answers (2)

ylpoonlg726
ylpoonlg726

Reputation: 16

Try this:

L = [1, 2, 3, 4, 5]
L2 = []
print(L)

k = 2   #the number of items to be modified
for x in range(0, len(L)-k+1):
    N = L.copy()
    for y in range(x, x+k):
        N[y] *= -1
    L2.append(N)
    print(N)

You can change the k value if you want.

Upvotes: 0

Roy2012
Roy2012

Reputation: 12543

Cool question. try this:

L = [1, 2, 3, 4, 5]

def foo(lst, inx):
    print(inx)
    new_l = lst.copy()
    new_l[inx] *= -1
    new_l[inx+1] *= -1
    return new_l

[foo(L, i) for i in range(4)]

The output is:

[[-1, -2, 3, 4, 5], [1, -2, -3, 4, 5], [1, 2, -3, -4, 5], [1, 2, 3, -4, -5]]

Upvotes: 2

Related Questions