Plajerity
Plajerity

Reputation: 161

Python Values replacement in list

I have to be making stupid mistake, but I really have no idea why it's working this way. Can anyone expain it to me please?

placement = [0]*4
for image in placement:
    image = 1
print(placement)

output:[0, 0, 0, 0]

Upvotes: 0

Views: 31

Answers (2)

Alex Lucaci
Alex Lucaci

Reputation: 630

When iterating with for in over an array, if modifying the resulted element from each iteration will not affect the original array. Use enumerate to iter over the array with the index and assign with the index

for index, image in enumerate(placement):
    placement[index] = image + 1

Upvotes: 2

Avish
Avish

Reputation: 4626

When you say:

image = 1

You're only changing the value of the variable called image; in other words, you're binding the name image to a new value. This doesn't affect the original list at all.

In more detail: when you say for image in placement, what happens is that on each iteration of the for-loop, the name image is bound to the value in the appropriate position in the list. Assigning to it again only re-binds it to some other value.

The for-loop above is equivalent to:

  image = placement[0]
  image = 1  # does not change placement[0]
  image = placement[1]
  image = 1  # does not change placement[1]
  image = placement[2]
  image = 1  # does not change placement[2]
  image = placement[3]
  image = 1  # does not change placement[3]

To change items in the list, you can assign to a specific index:

for i in range(len(placement)):
  placement[i] = 1  # assigns into a specific position in the list, changing its contents

Upvotes: 2

Related Questions