Reputation: 581
Few days ago I have been trying many ways and methods for at get desired behaviour of list in Python. I need to construct a method, which assigns and changes values in list at the same time it keeps size of list. let me explain
I have such a code.
A = [1,1,1,1,1]
B=[]
for i in range(0,len(A)):
for j in range(1,3):
val = j*2*A[i]
B.insert(i,val)
print(B)
The result I get:
[4, 2]
[4, 4, 2, 2]
[4, 4, 4, 2, 2, 2]
[4, 4, 4, 4, 2, 2, 2, 2]
[4, 4, 4, 4, 4, 2, 2, 2, 2, 2]
What I want to do!
take the first value of A-list in this case int 1
. then make some calculation by increasing a range function. val = 1*2*A[0] = 2
and set in the B-list, and continue val = 2*2*A[0] = 4
and set in B-list. then next val = 1*2*A[1] = 2
and val = 2*2*A[1] = 4
. I am expecting to have a output like this.
[2]
[4]
[2,2]
[4,4]
...............
Update:
I have updated a sample of code, this time a for-loop is added for construction of list A
but it runs into some problem.which I do not really understand why it does run with error list index out of range.
That is clear, when len(list A)
is 4
, len(list B)
becomes 5
. it is not expected list B
gets out of range?
A = []
B = []
for n in range(1,11):
A.append(n/n)
for i in range(0,len(A)):
B.insert(i, A[i])
for j in range(1,3):
for k, _ in enumerate(B):
B[k] = j*2*A[k]
print(B)
Output I get:
[2.0]
[4.0]
[2.0, 4.0] #<------- Not need it
[2.0, 2.0]
[4.0, 2.0] #<------- Not need it
[4.0, 4.0]
[2.0, 1.0, 4.0] #<------- Not need it
[2.0, 2.0, 4.0] #<------- Not need it
IndexError: list index out of range
Expected output.
[2.0]
[4.0]
[2.0, 2.0]
[4.0, 4.0]
---------------
I do not really know how to solve this type of problem, I appreciate any help...
Upvotes: 4
Views: 854
Reputation: 10860
you should put the insert
function in the outer loop, otherwise you insert not only for every element in A
, but also for every calculation step in range(1, 3)
i.e.
A = [1,1,1,1,1]
B=[]
for i in range(0,len(A)):
B.insert(i, A[i])
for j in range(1,3):
B[i] = j*2*A[i]
print(B)
or better Python:
A = [1, 1, 1, 1, 1]
B = []
for i, elmnt in enumerate(A):
B.insert(i, elmnt)
for j in range(1, 3):
B[i] = j * 2 * elmnt
print(B)
But why do yo want to write val = 1*2*A[0] = 2
into B[0] if you overwrite it anyway in the next step by val = 2*2*A[0] = 4
?
That doesn't make sense.
EDIT:
Latest agreement about what should be the expected behaviour:
A = [1, 1, 1, 1, 1]
B = []
for i, elmnt in enumerate(A):
B.insert(i, elmnt)
for j in range(1, 3):
for k, _ in enumerate(B):
B[k] = j * 2 * elmnt
print(B)
[2]
[4]
[2, 2]
[4, 4]
[2, 2, 2]
[4, 4, 4]
[2, 2, 2, 2]
[4, 4, 4, 4]
[2, 2, 2, 2, 2]
[4, 4, 4, 4, 4]
...or with numpy it's easier to change all values of an array at once:
import numpy as np
A = np.array([1, 1, 1, 1, 1], 'int')
B = np.array([], 'int')
for i, elmnt in enumerate(A):
B = np.append(B, elmnt)
for j in range(1, 3):
B[:] = j * 2 * elmnt
print(B)
[2]
[4]
[2 2]
[4 4]
[2 2 2]
[4 4 4]
[2 2 2 2]
[4 4 4 4]
[2 2 2 2 2]
[4 4 4 4 4]
Upvotes: 3