manyu
manyu

Reputation: 485

how does list modification works in python

I have list of 10 elements having a tuple of 2 elements I want to add to each tuple a value but when i write the following code to do so it seems that cumulative sum is caluculated . How is this happening. please help

# -*- coding: utf-8 -*-
i=0
k=10
count=[]
value=[1,2]
while i < k:
  count.append(value)
  i=i+1
t=[10,2]
i=0
#for item in count:
  #print item
while i <(len(count)):
  count[i][0]+=t[0];
  count[i][1]+=t[1];
  i+=1;

for item in count:
  print item

outpus is coming out to be

[101, 22]
[101, 22]
[101, 22]
[101, 22]
[101, 22]
[101, 22]
[101, 22]
[101, 22]
[101, 22]
[101, 22]

where as i expected it to be

[11, 4]
[11, 4]
[11, 4]
[11, 4]
[11, 4]
[11, 4]
[11, 4]
[11, 4]
[11, 4]
[11, 4]

Upvotes: 1

Views: 98

Answers (3)

Mike Ramirez
Mike Ramirez

Reputation: 10970

The problem is in how python uses memory, each time you append value to count, you're actually appending a reference to value's memory location. Whats happening is t[0] is being added to value[0] each time you loop through it. See it action below (same setup you used)

n [54]: for i, item in enumerate(count):
print count[i];
count[i][0] += t[0]
print count[i]
....:     
[1, 2]
[11, 2]
[11, 2]
[21, 2]
[21, 2]
[31, 2]
[31, 2]
[41, 2]
[41, 2]
[51, 2]
[51, 2]
[61, 2]
[61, 2]
[71, 2]
[71, 2]
[81, 2]
[81, 2]
[91, 2]
[91, 2]
[101, 2]

Instead for the output you want append just the list object itself [1,2] without assigning it to a variable.

Also, enumerate() (a python built-in) produces the index number and the item in the loop so you don't have to use the whiles everywhere.

Upvotes: 0

Keith
Keith

Reputation: 43054

That's because you actually have a list of ten references to the same (single) 2-item list. You are repeatedly adding to that same list in the second loop. You really want a new instance of a the sublist (and what you really have is a mutable list, not a tuple).

You could do this:

while i < k:
  count.append(value[:])
  i=i+1

To get new copies of the embedded list.

Upvotes: 3

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236124

Try this:

i=0
k=10
count=[]

while i < k:
  count.append([1,2])
  i=i+1

t=[10,2]
i=0

while i <(len(count)):
  count[i][0]+=t[0];
  count[i][1]+=t[1];
  i+=1;

for item in count:
  print item

The problem was in this line: count.append(value), you were adding the same mutable reference to [1, 2] to the count list, and kept updating it over and over again.

By replacing the line with count.append([1,2]) you make sure that each time a new, different list is added.

And by the way, you're not using tuples (as stated in the question) anywhere in your code, only lists.

Upvotes: 2

Related Questions