0

I'm trying to take two lists and use one list to make changes in the second list as the following code shows:

a = [1,2,3,4,5]
b = [0,0,0,0,0]

for aA, bB in zip(a,b):
    bB = aA*4
    
print(b)

I get the result b = [0,0,0,0,0], I want b = [4,8,12,16,20]

I know that you shouldn't modify containers while iterating with a for loop. But is there any work-around in python to be able to get the intended result of modifying a container?

4 Answers 4

1

Python unlike many other languages is dynamically typed as in you don't need to initialize prepopulated arrays(lists) before populating them with data. Also a standard convention is list comprehensions which in lamens are in-line loops that return a list.

a = [1,2,3,4,5]
b = [num * 4 for num in a]

This is equivilent to:

a = [1,2,3,4,5]
b = []
for num in a:
    b.append(num * 4)
Sign up to request clarification or add additional context in comments.

Comments

1

Why not use index?

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

The standard advice is "don't change a list while you're iterating over it". We say this because if you add or remove an element then the iterator will start doing weird hard-to-predict things. But that's not what's happening here: we're iterating over a and changing b, knowing in advance they're the same size, so there's no undefined or hard-to-understand behavior.

Comments

1

The values you want to put into b only depend on a, so there is no reason to initialize and iterate on b. You could do either:

# build list b as you go
b = []
for aA in a:
    b.append(aA*4)
print(b)

or

# use a list comprehension
b = [aA*4 for aA in a]
print(b)

Comments

1

Please try this:

b.append( aA*4)

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.