4

I want to set every Nth element in a list to something else.

(Like this question which is for Matlab.)

Here's an attempt with N=2:

>>> x=['#%d' % i for i in range(10)]
>>> x
['#0', '#1', '#2', '#3', '#4', '#5', '#6', '#7', '#8', '#9']
>>> x[0::2] = 'Hey!'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: attempt to assign sequence of size 4 to extended slice of size 5

How can I fix this? Slicing seems to expect an iterable, not just a single value.

Community
  • 1
  • 1
Jason S
  • 184,598
  • 164
  • 608
  • 970
  • 1
    This isn't an array, it's a list. That matters, because there is an array type in the standard library, as well as a different one in the common library `numpy`, and with a numpy `array`, `x[::2] = 'Hey!'` would actually have worked.. – DSM Apr 09 '13 at 18:46

2 Answers2

5

The right side of a slice assignment has to be a sequence of an appropriate length; Python is treating 'Hey!' as a sequence of the characters 'H', 'e', 'y', '!'.

You can be clever and create a sequence of the appropriate length:

x[::2] = ['Hey!'] * len(x[::2])

However, the clearest way to do this is a for loop:

for i in range(0, len(x), 2):
    x[i] = 'Hey!'
ecatmur
  • 152,476
  • 27
  • 293
  • 366
1

It is also possible with list comprehension:

x=['#%d' % i for i in range(10)]
['Hey!' if i%3 == 0 else b for  i,b in enumerate(x)]

This is appearently with n=3.

Finn
  • 198
  • 9