Python Code Challenges: Lists (Advanced) : Double Index | Learn Python 3 Pro Course

Hello guys.

I’m currently undergoing Python Code Challenges(Optional). At the part of Python Code Challenges: Lists (Advanced), for Double Index (the 4th challenges), I think the provided solution code can go wrong if the parameter “index” was -1.

So, the provided solution code look like this:

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], -1))

Which the output would be [3, 8, -10, 24, 3, 8, -10, 12]

And, my code looks like this, which may seen longer but as I tested there was no bug:

def double_index(lst, index): if index >= len(lst) or index < -len(lst): return lst else: lst.insert(index, lst[index] * 2) if index < 0: lst.pop(index) else: lst.pop(index+1) return lst print(double_index([3, 8, -10, 12], -1))

Which the output would be: [3, 8, -10, 24]

Just want to share with you guys and wanna know if there is a cleaner code for this challenge.

The exercise says:
The function should return a new list

you don’t return a new list, you modify the original list. If you are going to modify the list, the solution is even simpler, we can simply do:

``````lst[index] *= 2
``````

then we don’t even need `insert` and `pop`

I had this discussion once before on the forum, even if you want a new list (and not modify the original one) you should copy the list first, still a lot simpler then list slicing

I just found the post you mentioned here.
I didn’t notice that the exerice asks to return a new list instead of modifying the original one. Thanks for reminding.
But, I wonder what it means at the last line you wrote. If not using slicing as the provided soilution code, how the code would look cleaner?

You found the post, which contains a full sample code:

``````def double_index(lst, index):
# Checks to see if index is too big
if index >= len(lst):
return lst
else:
lst[index] *= 2
return lst
print(double_index([3, 8, -10, 12], 2))
``````

which looks pretty clean, no?

Yes, I’ve seen this code! But I thought this code modified the original list.
So, what I wanted to ask was how a cleaner code would be if the original list isn’t modified.

I thought this was also in the topic:

you can use whatever approach you prefer to copy the list. I will leave it to you to figure out what the right place is to make the copy of the list

Wow, thanks.

The code would probably look like this ?

lst = [3, 8, -10, 12] def double_index(lst, index): new_lst = lst.copy() if index >= len(lst): return lst else: new_lst[index] *= 2 return new_lst print(double_index([3, 8, -10, 12], -1)) print(lst)

yea, exactly.