Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
About list and method ....
#2
When you repeatedly do level2.append(level1), you keep putting another copy of the same list into the outer list.

Then when you modify level1, all the copies inside are changed. If you want them independent, you need to make different copies.

>>> inner = ["x"]
>>> outer = [inner]
>>> inner.append("z")  # Modifies the object that is inside "outer"
>>> outer
[['x', 'z']]
>>> inner = ["x"]
>>> outer = [inner[:]]  # contents are a copy of inner, not the same object
>>> inner.append("z")   # modifies inner, but not the object in outer
>>> inner
['x', 'z']
>>> outer
[['x']]
Fernando_7obink likes this post
Reply


Messages In This Thread
About list and method .... - by Fernando_7obink - Dec-22-2020, 03:46 AM
RE: About list and method .... - by bowlofred - Dec-22-2020, 04:02 AM
RE: About list and method .... - by Fernando_7obink - Dec-22-2020, 09:15 AM
RE: About list and method .... - by deanhystad - Dec-22-2020, 04:16 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  comtypes: how to provinde a list of string to a COM method zalanthas 0 1,045 Jun-26-2024, 01:27 PM
Last Post: zalanthas
  Question about List.reverse() method tomliuwhite 1 2,099 Dec-07-2021, 08:20 AM
Last Post: ndc85430
  Unable to use random.choice(list) in async method spacedog 4 5,038 Apr-29-2021, 04:08 PM
Last Post: spacedog
  print all method and property of list object engmoh 4 4,006 Oct-26-2019, 05:33 PM
Last Post: engmoh
  why my method doesn't find my List in the same class? Scorpio 2 3,053 Jan-31-2019, 05:21 PM
Last Post: Scorpio
  [Python Class] save method output to global file/list Vijay 3 6,529 Dec-23-2017, 03:20 AM
Last Post: Vijay

Forum Jump:

User Panel Messages

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