Can this loop be done in a list comprehension?

121 Views Asked by At

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?

3

There are 3 best solutions below

0
AudioBubble On BEST ANSWER

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]
1
BrokenBenchmark On

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))]
3
MK14 On

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