0

I'm trying to use a for loop in order to modify values in a list, based on values on a second list. Hence I though that the "zip" function would come in handy, however I'm not getting the result I'm expecting. See an example here:

list_a = [0,0,0,0]
list_b = [1,2,3,4]

for a, b in zip(list_a, list_b):
a = b*2

I though that this modifies list_a, however it does not. My understanding was that, inside the loop, "a" was first equal to list_a[0], then list_a[1], etc, in other words views of the list.

I have actually 2 questions:

a) what are "a" and "b" inside the loop, if they are not views of the two lists?

b) is there a pythonic way of implementing this loop (i.e. something different from looping over i in range(len(list_a))?

4
  • pythonic way ? probably do your operations in a comprehension and create a new list, assigning to list_a at the end. Commented Apr 7, 2019 at 18:12
  • 1
    a=.. does not modify a[0]. It just assigns a new value to the variable. view is a numpy array concept, not a list one. Commented Apr 7, 2019 at 18:14
  • 2
    "was first equal to list_a[0], then list_a[1], etc, in other words views of the list." No, they are not views. list_a[i] returns the object contained by that index in the list. a = list_a[0] makes the name a reference some object, that happens to be the first element of list_a, but that object has no knowledge of that Commented Apr 7, 2019 at 18:15
  • They are just another references, not pointers. Commented Apr 7, 2019 at 18:15

1 Answer 1

2

You can try something like:

list_a = [0,0,0,0]
list_b = [1,2,3,4]

for i, b in enumerate(list_b):
    list_a[i] = b*2

You can get the same result with:

[b*2 for b in list_b]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.