Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
lists in list
#1
hi I make a list in list and append in [0] index a value. but it appends in all index. can andybody know why?
code:
matrix=[[1]]*3
print(matrix)
matrix[0].append(2)
print(matrix)
output:
Output:
[[1], [1], [1]] [[1, 2], [1, 2], [1, 2]]
if I try in this way I get this output
code:
matrix=[]
for i in range(3):
++++list=[1]
++++matrix.append(list)
print(matrix)
matrix[0].append(2)
print(matrix)
output:
Output:
[[1], [1], [1]] [[1, 2], [1], [1]]
why difference beetwen two output? thanks.
Reply
#2
Lists are mutable. When you copy them with [[3]] * 3 it copies three references to the same list. Use a list comprehension instead: [[3] for sublist in range(3)]. With a list comprehension, the sub-list is reevaluated each time through the loop, giving you three independent sub-lists.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  List all possibilities of a nested-list by flattened lists sparkt 1 878 Feb-23-2023, 02:21 PM
Last Post: sparkt
  user input values into list of lists tauros73 3 1,023 Dec-29-2022, 05:54 PM
Last Post: deanhystad
  returning a List of Lists nafshar 3 1,014 Oct-28-2022, 06:28 PM
Last Post: deanhystad
  Creating list of lists, with objects from lists sgrinderud 7 1,561 Oct-01-2022, 07:15 PM
Last Post: Skaperen
  How to efficiently average same entries of lists in a list xquad 5 2,069 Dec-17-2021, 04:44 PM
Last Post: xquad
  sorting a list of lists by an element leapcfm 3 1,805 Sep-10-2021, 03:33 PM
Last Post: leapcfm
  behavior list of lists roym 5 2,034 Jul-04-2021, 04:43 PM
Last Post: roym
  List of lists - merge sublists with common elements medatib531 1 3,353 May-09-2021, 07:49 AM
Last Post: Gribouillis
  Sort List of Lists by Column Nju 1 10,047 Apr-13-2021, 11:59 PM
Last Post: bowlofred
  Creating list of lists from generator object t4keheart 1 2,161 Nov-13-2020, 04:59 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

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