0

I want to use the last element of a list in a for loop to generate new element. Here is a toy example of my problem:

  a = [1]
  a += [a[-1]+i for i in range(10)]

but it only consider 1 as last element and does not go through for loop to find the new last element. Could you please tell me how to solve this problem?

2 Answers 2

1

I run the code and got the following answer:

In [2]: a = [1]

In [3]:  a += [a[-1]+i for i in range(1,10)]

In [4]: a
Out[4]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2
  • No, for example the 4th element should be 4 not 3.
    – user36729
    Commented Apr 8, 2017 at 17:49
  • 1
    It's because the range function generates 0 to 9, so if you start from a += [a[-1]+i for i in range(1,10)] , you will get the output [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    – babu7
    Commented Apr 8, 2017 at 17:51
0

Try this:

a = [1]
for i in range(10):
  a.append(a[-1]+i)
print(a)

Using list comprehension won't take the new last value of the array on each new iteration, but using a normal for loop will.

2
  • I just didn't want to have for loop like this to run the code faster.
    – user36729
    Commented Apr 8, 2017 at 17:49
  • I don't think this is any slower than list comprehension. What you are doing above is also a loop, just within a list comprehension.
    – abagshaw
    Commented Apr 8, 2017 at 17:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.