1

Comming from this question Adding the last position of an array to the same array

I was curious if the mentioned loop can be done in a list comprehension?

array = [3,4,2,5,4,5,8,7,8,9]
value = 10

for i in range(1,10):
   array[i] = array[i-1] + value

I thought maybe with the walrus operator.

My attempt gave me an error which lead to cannot-use-assignment-expressions-with-subscript

[array[count] := val if count == 0 else array[count] := array[count-1] + value for count,val in enumerate(array)]

Any ideas?

RSale
  • 463
  • 5
  • 14

3 Answers3

1

The for-loop only uses the first element and overwrites array with brand new items. The very same outcome can be achieved using the below list comprehension:

array = [array[0] + i*value for i in range(len(array))]

Output:

[3, 13, 23, 33, 43, 53, 63, 73, 83, 93]
0

We can make the observation that, if our resulting array is result, then result[i] = array[0] + i * value.

For example:

  • result[0] = array[0]
  • result[1] = result[0] + value = array[0] + 1 * value
  • result[2] = result[1] + value = array[0] + 2 * value
  • etc.

It follows from the code that this can generally be expressed as:

  • result[0] = array[0]
  • result[i] = result[i - 1] + value for i > 0.

Then, the list comprehension becomes:

result = [array[0] + i * value for i in range(len(array))]
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
0

The error occured because array[count] is not a variable identifier, it is instead a position in the list array and thus you can't assign anything to it.

Instead you can use the following...

array = [3,4,2,5,4,5,8,7,8,9]
value = 10

res = [(first_val := array[count]) if count==0 else array[count-1]+(count*value) for count,val in enumerate(array)]

print(res)
print(first_val)

Output:-

[3, 13, 14, 12, 15, 14, 15, 18, 17, 18]
3
MK14
  • 481
  • 3
  • 9
  • MK14, I got your result with another lc.However, this is not the same as the result from the above loop. – RSale Jan 03 '22 at 00:02
  • I just ran that code and got ```[3, 13, 23, 33, 43, 53, 63, 73, 83, 93]``` – RSale Jan 03 '22 at 22:43
  • @RSale Found the bug, it was in the line `array[count-1] + value`, here the elements from the main array are directly taken, but in your code, the elements are constantly being updated after adding the value, thus that's why it is was giving a different answer. – MK14 Jan 03 '22 at 22:58