Puzzle 10 Will It Fit?
Python Brain Teasers — by Miki Tebeka (19 / 40)
👈 A Simple Math | TOC | Click the Button 👉
a = [1, 2, 3, 4]
a[1:2] = [10, 20, 30]
print(a)
Guess the Output
IMPORTANT
Try to guess what the output is before moving to the next page.
This code will print: [1, 10, 20, 30, 3, 4]
Python’s slicing operator is half open ([) in math), meaning you’ll get from the first index up to but not including the last index. a[1:2] is in size 1, yet we assign a list of size 3 to it.
The assignment documentation is a bit hard to read (see below if you’re interested). Here’s an excerpt (my clipping and emphasis):
If the target is a slicing: … Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence …
In short, when you write a[1:2] = [10, 20, 30] it’s like writing a = a[:1] + [10, 20, 30] + a[2:].