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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Duplicate of https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list – cs95 Jun 25 '19 at 16:28

3 Answers3

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)
static const
  • 953
  • 4
  • 16
0

Modify your for loop to create a new list each time

for p in legal:
    new = state + [p]
    print(new)
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
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 :)

Ash Oldershaw
  • 302
  • 2
  • 13