Double index

I ended up doing it a bit differently. Would any issues arise from this? Maybe it just isn’t as elegant as using len()?

def double_index(lst, index):
  try:
    if lst.count(lst[index])>=1:
      lst[index] = (lst[index])*2
      return lst
  except IndexError:
    return "Your index is out of range!"

what is the purpose of count? So far i can determine, not much.

here:

if lst.count(lst[index])>=1:

lst[index] can still throw an index error here, so that is before .count() has even doing anything.

It seems you currently attempt two approaches: verifying the index exist and catching the error. Feels a bit duplicate to do both.

1 Like

You’re right, I was trying to count the amount of times the index appeared (if at all) and replace at that index (if it appeared at all). I thought that was what enabled the “if” function.

Are you saying I can remove that entire line and just do a try/except function?
EDIT: Yeah, I totally see what you mean.

def double_index(lst, index):
  try:
    lst[index] = (lst[index])*2
    return lst
  except IndexError:
    return lst,"Your index is out of range!"

worked completely better.

index refers to the position of an element in a list. Indexes are unique, the first element is at index 0, the second element at index 1 and so forth

plus, doing lst[index] will attempt to retrieve the value of the list, which can be a problem if the index doesn’t exist.

exactly.

like i said: either verify the index exist (using len() for example) before attempting to access the list with that index (lst[index]) or use try/except.

That are the the two ways to go.

Thank you for your help.
For some reason, I was doing the “if” function to trigger an error so I could catch it with “except”.
I didn’t realize that it would error out anyway; so I ended up doing more work than needed.

But now you seem to understand it better :slight_smile: Nice job :slight_smile:

2 Likes