Is there a right way to index a list

My code worked find, but I’m unsure if I should have gone about indexing in a different method.
Below is a function for writing all odd index items in a new list

#Codecademy solution
def odd_indices(lst):
  new_lst = []
  for index in range(1, len(lst), 2):
    new_lst.append(lst[index])
  return new_lst
#My solution
def odd_indices(lst):
  new_lst = []
  for index in lst[1:len(lst):2]:
    new_lst.append(index)
  return (new_lst)

You can see I’ve gone about indexing differently. Is this an ok way to do it, or could it have problems?

There are a couple of “problems”. First, using list slicing will give the values from the list, not the indexes. So index isn’t a very logic variable name.

secondly, using list slicing already gives back the list with the right values. So the whole for loop becomes redundant.

1 Like

Oh I see, so I could have even written:

#My solution
def odd_indices(lst):
  new_lst = lst[1:len(lst):2]
  return (new_lst)

!!!
Thank you for solving that I understand it better already

You can even skip the len(lst) part with [1::2] .

1 Like