Double Index

Duble Index is exercise #4 from Advanced Python Code Challenges: Lists

Difficult Python Code Challenges involving Lists
Here is the link:

I don’t understand specifically this code block that eventually returns a list [3, 8, -20, 12]:

new_lst = lst[0:index]

Adds double the value at index to the new list


Adds the rest of the original list

new_lst = new_lst + lst[index+1:]

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

Hello @coursesurfer26754.

This code effectively sets new_lst to every element in the original list before the item at index:

org_lst = [1, 2, 3, 4, 5, 6]
index = 2#in the org_lst that is the number 3
new_lst = [0:index]
print(new_lst)#this prints [1, 2] (as these are the elements of the original
#list that come before the item at index (which happens to be 3)

This just appends the item from original list at the position index, doubled:

# take the example above
new_lst.append(org_lst[index] * 2)
# new_lst is now equal to [1, 2, 6](the elements before the item at index
#and the item at index, doubled (in this case it was three doubled, so six

This just adds the rest of the org_lst (all elements after the item at the position index), to the new list (new_lst).
I hope this helps!

1 Like

Can I use this instead
new_lst = new_lst + lst[3:]

Have you tried this. Depending on the way you wrote it, it may well throw an error since new_lst has not been defined (so how could it be used?)

Your slice command also appears to be opposite way around this time. list[3:] means start at index 3 and slice to the end of the list.
The original was [:2] which is start at the beggining of the list and stop before index 2.

Why not run these statements and print the output?

1 Like

To add onto what @tgrtim said, in this particular case, you could, however, functions are meant to be specific to one case; they’re meant to be able to be used in every situation where one needs that to happen.