4
seats = 4  # user can choose an even input, I put 4 for this example
rows = 4  # user can choose an even or odd input, I put 4 for this example
seats_in_row_list = [i for i in string.ascii_uppercase[:seats]]
main_seat_list = [seats_in_row_list for i in range(rows)]

The output is:

[['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D']]

But when I try to change 'A' to 'X' in the first list all of the lists change:

[['X', 'B', 'C', 'D'], ['X', 'B', 'C', 'D'], ['X', 'B', 'C', 'D'], ['X', 'B', 'C', 'D']] 

What I'm looking for is this output:

[['X', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D']]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 3
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – GoodDeeds Mar 09 '20 at 13:09
  • use `main_seat_list = [seats_in_row_list.copy() for i in range(rows)]` – Rakesh Mar 09 '20 at 13:11
  • @GoodDeeds It's similar, but not a duplicate. The lists in that question have repeated values created from list multiplication, and none of the answers mention `list.copy()`, which is the right solution here. – wjandrea Mar 09 '20 at 13:13
  • 1
    @wjandrea You are right, I retracted my vote. But I think the link serves as a useful reference to understand the cause of the issue. – GoodDeeds Mar 09 '20 at 13:15

2 Answers2

4

Use copy method to have a copy of the individual list before assigning

main_seat_list = [seats_in_row_list.copy() for i in range(rows)]
omuthu
  • 5,948
  • 1
  • 27
  • 37
2

If you aren't using seats_in_row_list for anything other than the construction of main_seat_list, you should just inline the definition. Calling list here would be simpler than using a list comprehension.

seats = 4
rows = 4
main_seat_list = [list(string.ascii_uppercase[:seats]) for i in range(rows)]
chepner
  • 497,756
  • 71
  • 530
  • 681