1

Language is Python. I am trying to add 'a' to all of the values in a list 'sumarr'.

Here is my code:

for b in sumarr:
    b+=a

Why does this not work? I know I can use list comprehensions like this:

sumarr = [b+a for b in sumarr]

But why does the first method not work?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Vidit Gautam
  • 97
  • 1
  • 5

2 Answers2

0

Because this is not how python works.

I am trying to add 'a' to all of the values in a list 'sumarr'

There are methods defined in python Data Structure: here the documentation python 3.9.0

These are some official ways you can use to add elements in list.

# example 1.
new_list = []
for i in range(n):
  new_list.append(i) 

# List comprehension:
new_list = [i for i in range(n)]

# example 2.
lang = "Python"
a = []
for e in lang:
    a.append(ord(e))

b = [ord(e) for e in lang]

print(a)
print(b)
Lord-shiv
  • 1,103
  • 2
  • 9
  • 19
-2

b is a local variable - a reference of the list item, not the actual item in list.

If you do print( b += a ) you will see the expected number, but it won't put that result back into your list.

#! /usr/bin/env python3

sumarr = [1, 2, 3, 4]
a = 3

for b in range( len(sumarr) ):
    sumarr[b] += a

for b in sumarr:
    print( b )

4
5
6
7

Doyousketch2
  • 2,060
  • 1
  • 11
  • 11
  • "a local copy of the list item, not the actual item in list." Absolutely not true. It is the same object in the itself. Iterating over a list does not create copies. The rest of your answer is fine, but that first part is just not true. – juanpa.arrivillaga Nov 24 '20 at 08:14
  • It's not a deep copy, but a pointer to the address. b is a variable that points TO the item - it's not THE item. – Doyousketch2 Nov 24 '20 at 08:19
  • No **it isn't a copy at all**. Python *doesn't have pointers*. All variables act like references, yes, but that isn't relevant here and just obscures the straight-forward semantics. You can prove this easily: `data = [[]]` then `for sub in data: sub.append(42)` then `print(data)`. Of course, *assignment doesn't mutate*, which is the reason why simply assigning to a local variable has no visible effect on the list. So if I did, `for sub in data: sub = [99]` and `print(data)` it won't change – juanpa.arrivillaga Nov 24 '20 at 08:20