0

I have question about using nested single line for loop in python. In particular, I have the followings:

A = [[tmp1[a][b] / tmp2[a] for b in range(0,10)] for a in range(0,20)]

According to Here, the single line for loop is equivalent as

for a in range(0,20):
    for b in range (0, 10):
        A.append(tmp1[a][b] / tmp2[a])

However, python gives me the following error:

AttributeError: 'numpy.ndarray' object has no attribute 'append'.

How should I modify the structure so that I use double for loop instead of single line nested for loop?

Update:

A=[]
for a in range(0,20):
    B = []
    for b in range (0, 10):
        B.append(tmp1[a][b] / tmp2[a])
   A.append(B)
Community
  • 1
  • 1
wrek
  • 1,061
  • 5
  • 14
  • 26
  • 4
    You did not *initialize* `A` properly... You forgot the `A = []` part. – Willem Van Onsem Feb 21 '17 at 19:15
  • 3
    It is not a single-line `for` loop; it is a list comprehension. They both simply use the same keyword. – chepner Feb 21 '17 at 19:15
  • Append is for native `list` – Jean-François Fabre Feb 21 '17 at 19:15
  • 1
    You're confusing two very similar lines of of code - the first builds a list of lists, the second a single list: `A = [[tmp1[a][b] / tmp2[a] for b in range(0,10)] for a in range(0,20)]` is not the same as `A = [tmp1[a][b] / tmp2[a] for b in range(0,10) for a in range(0,20)]` – Eric Feb 21 '17 at 19:35
  • @Eric, please see my update. Do you agree that the update is equivalent to `A = [[tmp1[a][b] / tmp2[a] for b in range(0,10)] for a in range(0,20)]` – wrek Feb 21 '17 at 19:42
  • 1
    @wrek :Yes, your update is correct – Eric Feb 21 '17 at 22:15

2 Answers2

1

if you do :

for a in range(0,20):
    for b in range (0, 10):
        A.append(tmp1[a][b] / tmp2[a])

A should be a list to have the attribute append:

A=[]
for a in range(0,20):
    for b in range (0, 10):
        A.append(tmp1[a][b] / tmp2[a])

This method is different it's a list comprehension (a way to create the list) :

A = [tmp1[a][b] / tmp2[a] for a in range(0,20) for b in range(0,10)]
Dadep
  • 2,796
  • 5
  • 27
  • 40
1

There are two ways of setting up your list comprehension

This

A = [tmp1[a][b] / tmp2[a] for a in range(0,20) for b in range(0,10)]

produces a flat list.

This:

B = [[tmp1[a][b] / tmp2[a] for b in range(0,10)] for a in range(0,20)]

produces a nested list.

Be sure to note the swap between the two for statements. In the nested case the slowly changing variable comes last, in the flat case it comes first.

The equivalent loops are

A=[]
for a in range(0,20):
    for b in range (0, 10):
        A.append(tmp1[a][b] / tmp2[a])

and

B=[]
for a in range(0,20):
    inner=[]
    for b in range (0, 10):
        inner.append(tmp1[a][b] / tmp2[a])
    B.append(inner)
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99