What I want to do is pretty simple, I have a list list1 = [a,b,c,d] and I want to create another variable called finalList=[[a,0],[b,0],[c,0],[d,0]] Here's the code I did for this operation:
finalList = [["none",0]]*len(list1)
for i in range(len(list1)):
finalList[i][0] = list1[i]
finalList
this is the output I get:
[['30_39', 0],
['30_39', 0],
['30_39', 0],
['30_39', 0],
['30_39', 0],
['30_39', 0]]
knowing that the content of list1 is:
['Low_Class', '40_49', '50_59', 'Marital_Status', '60_plus', '30_39']
I don't know why it fills it with the last element only !!
CodePudding user response:
I'm not sure why it is filling the list with the last item, but there is a simple way to do this using a list comprehension:
Something like this:
finalList = [[item,0] for item in list1]
This will create a list with your desired output.
CodePudding user response:
When you do:
finalList = [["none",0]]*len(list1)
You are not making a copy of ["none",0]
, but a reference to it. So, what is really happening is that finalList
containes a list of references to the single item ["none",0]
.
Solution
You can do a simple list comprenhention to make a new ["none",0]
for each position like this:
finalList = [["none",0] for _ in range(len(list1))]
This creates a new ["none",0]
each time.
Extra explanation
When python runs this line:
finalList = [["none",0]]*len(list1)
It creates the object ["none",0]
, but it puts a reference to it (because lists are treated by reference) into finalList
. Then, when the multiplication (*len(list1)
) comes, it copies that refernece (not the object). Whenever you access finalList
all the positions contains a references to the same object. So, in each iteration of the comming loop you are changing the same object (this is why you are seeing the last value, because its the last you are setting). Finally when you print the list, it is really printing the same item several times (that's why it "seems" like is setting that last value in "all" elements).