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.

1
  • 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.. Commented Apr 9, 2013 at 18:46

2 Answers 2

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!'
Sign up to request clarification or add additional context in comments.

2 Comments

@JasonS there is a one-liner (added above) but it's significantly less readable.
I think the first solution is quite Pythonic, personally.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.