Home > Back-end >  Replacing every other position in a list
Replacing every other position in a list

Time:01-23

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", "A", 6, "A", 8, "A", 10]

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

CodePudding user response:

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)/)

CodePudding user response:

Try using a list comprehension paired with enumerate:

l = ["A" if i % 2 == 0 else elem for i, elem in enumerate(l)]

This replaces every element with an odd index (odd numbers % 2 will equal 0) with the letter "A", and leaves the remaining elements as they are. Enumerate loops over the original iterable, but includes an index element as well.

  •  Tags:  
  • Related