0

I'm stuck in a problem in Python. I want to add a list of variables to a list in order to have multiple lists, this way (it's an example):

legal = [1, 2, 3, 4, 5]
state = [0, 9]
for p in legal:
    new = state
    new.append(p)
    print(new)

Output I have with this code:

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

Output I look for:

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

Is there a way to keep the original list without redefining it in the loop?

1

3 Answers 3

1
legal = [1, 2, 3, 4, 5]
state = [0, 9]
for p in legal:
    print(state + [p])

When you call .append(val) on a list, it does it in-place and updates the original list. So a better way would be to create a new list inside of the loop,

for p in legal:
    tempList = state + [p]
    print(tempList)
Sign up to request clarification or add additional context in comments.

Comments

0

Modify your for loop to create a new list each time

for p in legal:
    new = state + [p]
    print(new)

Comments

0

A useful tool you might like to use is something called list comprehension.

It's a way of building lists as you go.

Here is something that will create a list of your lists

output = [state + [i] for i in legal]

This is something you can play with later on in your code, if you need to.

Then to print them all off you can write

for list in output: print list

Which will print your output off.

Hope this helps! There are other answers here but using list comprehension is a great way to do things in Python :)

Comments

Your Answer

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