Thread Shed project

I’m currently doing a strings project Thread Shed

https://www.codecademy.com/courses/learn-python-3/projects/thread-shed

i = 0
for element in transactions_clean:
  if transactions_clean.index(element) < 100:
    customers.append(transactions_clean[i])
    sales.append(transactions_clean[i+1])
    thread_sold.append(transactions_clean[i+2])
    i += 4
  else:
    break
i = 0
for element in transactions_clean:
  if transactions_clean.index(element) < 100:
    customers.append(transactions_clean[i])
    sales.append(transactions_clean[i+1])
    thread_sold.append(transactions_clean[i+2])
    i += 4

When executing the first code, it gives me the right result I wanted. However, when executing the code below it gives me error saying,

Traceback (most recent call last):
File “script.py”, line 135, in
customers.append(transactions_clean[i])
IndexError: list index out of range

But when I tried this on Pythontutor.com with much less elements in the list (I shrink it to 40 elements in total), it works fine but with the program continuously checking through the for statement and if statement until the loop has iterated till the end of the list. But still it returns me the right result I want to see. Why is it causing me such error??

The condition in your if-statement doesn’t strike me as something you’d want to test. It’s also really inefficient to search through the list every time you do that, if you wanted to know the location then you could track that by counting (adding 1 each time) instead. But you don’t want the location. You also risk finding the wrong location if there are duplicate values… there probably isn’t in this case, but it goes to further show that this isn’t something you want. Having a hard-coded number is weird too, you’d either use a number that is okay for all possible inputs, or obtain the number from the input.

As for the problem you’re asking about, your error message says quite a lot. It says your index isn’t valid for that list, and it says where in your code… so you might want to find out which index you used and what the valid indices are, and you can also look at how you obtained that index and consider whether that was a valid strategy.

1 Like