TBH, the Double Index challenge was too advanced for me.
Advanced Python Code Challenges: Lists
def double_index(lst, index):
if index >= len(lst):
return lst
else:
new_lst = lst[0:index]
new_lst.append(lst[index]*2)
new_lst = new_lst + lst[index + 1:]
return new_lst
print(double_index([3, 8, -10, 12], 2))
So I did a research of why the code is as follows. I decided to make sense of each and every line:
index represents the position of values in the lst>>>
def double_index(lst, index):
so, if index number value is bigger than the len of the list which has 4 numbers [3, 8, -10, 12], original list remains >>>
if index >= len(lst):
return lst
Or else, returns a new list with positions 0 to index where INDEX is the POSITION assigned - in this case 3rd position = 2. This new_lst is assigned the slice beginning at index 0 up to, but not including index 2. The value assigned to new_lst now is [3, 8].>>>
else:
new_lst = lst[0:index]
Append double the value at index. That line appends the doubled value of the element - located at index 2. The value of the original list at index 2 is -10, so -20 is appended. Now the value of new_lst is [3, 8, -20]. It doesn’t REPLACE, because we already cut the slice UNTIL index 2, so new double value appears there!
new_lst.append(lst[index]*2)
Adds the rest of the original list, from 1 on… And adds lst[index + 1:] == which is [12] . The slice needs to include the elements from index 3 through the end of the list since we already have the elements at index 0, index 1 and index 2, already in lst[0:index]. Index is the index of the element position we wanted to double not the value of the element. To get the remainder of the list concatenated to our new_lst we start our slice at the element after index 2 by adding 1 to index. When we concatenate the values: new_lst = [3, 8, -20] + [12] we get [3, 8, -20, 12] as the value assigned to new_lst which is then returned.>>>
new_lst = new_lst + lst[index + 1:]
return new_lst
I would not have done this code on my own, even though I practice a lot on each and every lesson.
I guess with time, and learning the rules and logic of the language it will be easier.
If i made a mistake in my conclusions (which I also gathered from research), please correct.