pr94
pr94

Reputation: 1393

Change values of a list slice with one new value

I would like to update a slice of a Python list with a defined value. I'd prefer to avoid a loop as the program needs to be as efficient as possible.

Thanks,

I tried this:

x = [0]*20
x[10:15] = 1

# and:
x = [0]*20
x[10:15] += 1


# first code gets
TypeError: can only assign an iterable

# second code gets
TypeError: 'int' object is not iterable

Upvotes: 0

Views: 3129

Answers (2)

Alain T.
Alain T.

Reputation: 42143

You could produce a source array of the appropriate size using a list comprehension

# assign a constant value
x[10:15] = [1] * len(x[10:15])

# perform a calculation
x[10:15] = [ n+1 for n in x[10:15] ]

Upvotes: 2

Sheldore
Sheldore

Reputation: 39042

Lists do not support vectorized operations (second code) or multiple indices assignment (first code). I think you might be interested in using NumPy array here

import numpy as np

x = np.zeros(20)
x[10:15] = 1
# [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 1. 0. 0. 0. 0. 0.]

x = np.zeros(20)
x[10:15] += 1
# [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 1. 0. 0. 0. 0. 0.]

Nevertheless, if you want to stick to lists, you can do your desired changes using a for loop as

x = [0]*20
for i in range(10, 15):
    x[i] = 1

Upvotes: 3

Related Questions