Welcome to the forum. Might I suggest that, if you’re stuck with this, you go back and review the Lists content - specifically around slicing.
To understand what’s happening, look at each line individually.
Our function call is
double_index([3, 8, -10, 12], 1). Here’s what Python is doing.
Step 1: Evaluate
if index >= len(lst):
index = 1, and
len(lst) = 4, so this evaluates to
False and we run the code in the
Step 2: Run the
new_lst = lst[0:index]
To start with,
lst = [3, 8, -10, 12] and
index = 1. These are the arguments we passed into the function.
What we’re doing is we’re taking a slice of
lst, and assigning it to
lst[0:index] is the same as
lst[0:1], so we slice out every item in the list from index
0 up to but not including index
lst[0:1] = , so
new_lst = .
Now, we need to evaluate
index is still
lst = 8.
Next, we multiply that value by 2 - so we get
16 - and we append this to
The result is that
new_lst = [3, 16].
new_lst = new_lst + lst[index+1:]
Here, we’re simply concatenating the existing
new_lst with another slice from
Lets work out the slice first.
We still know that
index = 1, so
index+1 = 2. We can then work out that
lst[index+1:] is the same as
lst[2:], so we’re taking a slice of every item in
lst from index 2 to the end of the list.
lst[2:] = [-10, 12], so when we concatenate them we get
new_lst = [3, 16] + [-10, 12] = [3, 16, -10, 12].
We return the value
[3, 16, -10, 12] to our
print() call, and so you get the output
[3, 16, -10, 12] in the console.
Hopefully, this is now obvious, but just in case it isn’t…
+1 means that the slice we are adding on to the end of
new_lst includes the list item we’re doubling.
The value of
index never changes from
1. If our slice is
lst[index:], we get
[8, -10, 12]. This is wrong, because our goal is to take a list and double the value at a specific index in that list. Without the
+1, what we’re doing is injecting an additional value - of double the target index - into the list at that position.
Does that clarify it at all?