Python Forum
Append only adding the same list again and again
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Append only adding the same list again and again
#2
This is because your functions like rotate_clockwise_90 isn't returning a copy of the list, it's modifying the list and then handing it back. So you only have one list that you're modifying over and over again. And your big list just has that one appended multiple times.

You should decide if your functions should be returning copies, or if they should be modifying the passed-in function. Then either the caller or function can be making a copy.

outer_list = []
sublist = ['a']   # list brackets here make a new list
outer_list.append(sublist)
sublist[0] = 'b'  # modifying an element of the list, not a new list
outer_list.append(sublist)
print(outer_list)

# If you don't want to modify the passed-in list, make a copy
sublist = sublist.copy()
sublist[0] = 'c'  # This is modifying only the new list, not the old one
outer_list.append(sublist)
print(outer_list)
Output:
[['b'], ['b']] [['b'], ['b'], ['c']]
Reply


Messages In This Thread
RE: Append only adding the same list again and again - by bowlofred - Jun-17-2020, 03:12 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  append str to list in dataclass flash77 6 498 Mar-14-2024, 06:26 PM
Last Post: flash77
Question How to append integers from file to list? Milan 8 1,457 Mar-11-2023, 10:59 PM
Last Post: DeaD_EyE
  Adding values with reduce() function from the list of tuples kinimod 10 2,677 Jan-24-2023, 08:22 AM
Last Post: perfringo
  read a text file, find all integers, append to list oldtrafford 12 3,618 Aug-11-2022, 08:23 AM
Last Post: Pedroski55
  Using .append() with list vs dataframe Mark17 7 10,538 Jun-12-2022, 06:54 PM
Last Post: Mark17
  Adding a list to Python Emailing Script Cknutson575 4 2,325 Feb-18-2021, 09:13 AM
Last Post: buran
  adding numbers in a list Nickd12 2 2,212 Jan-15-2021, 12:46 PM
Last Post: Serafim
  How to append multiple <class 'str'> into a single List ahmedwaqas92 2 2,355 Jan-07-2021, 08:17 AM
Last Post: ahmedwaqas92
  Adding List Element if Second part of the List Elements are the Same quest_ 3 2,472 Nov-25-2020, 04:33 PM
Last Post: bowlofred
  How to append to list a function output? rama27 5 6,766 Aug-24-2020, 10:53 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020