Python Code Challenges: Lists (Advanced)

Hey everyone!
During the exercise n° 4 of the Python Code Challenges: Lists (Advanced), I found probably another solution to solve the exercise in a more easier way (I’m a newcomer to Python3, so I’m not so sure :slight_smile: ).
The original solution was:

def double_index(lst, index):
  # Checks to see if index is too big
  if index >= len(lst):
    return lst
  else:
    # Gets the original list up to index
    new_lst = lst[0:index]
 # Adds double the value at index to the new list 
  new_lst.append(lst[index]*2)
  #  Adds the rest of the original list
  new_lst = new_lst + lst[index+1:]
  return new_lst

print(double_index([3, 8, -10, 12], 2))

And my solution is:

def double_index(lst, index):
  if index + 1 <= len(lst):
    lst[index] *= 2
  return lst

print(double_index([3, 8, -10, 12], 2))

Someone can review this few lines of code?
Thank you very much in advance.

Have a nice day :smiley:

Your solution is certainly quicker (and shorter); however it does modify the original list (the function’s input). This is sometimes considered bad practise, as in the future, you may want to access this list. That’s the reason CC’s solution goes about creating a whole new list. As for which one is better, that really depends on how you prefer to code…

1 Like

I always struggle with this. Even if we do not want to modify the list, I would do something like:

def double_index(lst, index):
  lst = lst.copy()
  if index + 1 <= len(lst):
    lst[index] *= 2
  return lst

x = [3, 8, -10, 12]
print(double_index(x, 3))
print(x)

So its clear that we are copying the list. The slicing would confuse me if I had to look at after three months

or you could argue (depending on the requirements), to add another parameter, like so for example:

def double_index(lst, index, modify = True):
  if not modify:
      lst = lst.copy()
  if index + 1 <= len(lst):
    lst[index] *= 2
  return lst

x = [3, 8, -10, 12]
print(double_index(x, 3))
print(x)
1 Like

Fair, fair. I think the lesson is partly geared towards list slicing practise, but very true.

1 Like