Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing every other position in a list

I'm trying to make something that allows me to replace every other position in a list with a single item:

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l[::2] = "A"
print(l)

I'm expecting something like:

["A", 1, "A," 3, "A", 5, "A", 7, "A", 9, "A"]

I've tried different positions of indexing [::] but either get an error or a result that doesn't include the rest of the list.

Instead I get this:

ValueError: attempt to assign sequence of size 1 to extended slice of size 2
like image 958
Nenga Avatar asked Dec 04 '25 06:12

Nenga


1 Answers

The slice is correct, but you need to provide a sequence with enough elements to fill all the elements.

l[::2] = ["A"] * math.ceil(len(l)/2)
like image 59
Barmar Avatar answered Dec 06 '25 22:12

Barmar