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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With