Iterating trough a list of strings (Python)

While I was doing a Python exercise at the learn Python course I got stuck during one of the exercise requirements. In this exercise I should create a loop that is able to iterate trough a list of strings and append each string to other lists that should contain that type of string. For example if the string is a name, it should be appended to the customer list, if its a money value, it should be appended to the price list. I tried to think of many solutions, for example:

index = 0
for transaction in transactions_clean:
    customers.append(transaction[index])
    index += 1
    sales.append(transaction[index])
    index += 1
    thread_sold.append(transaction[index])
    index += 1
    date.append(transaction[index])
    if index == 700:
      break

or

transactions_list = []
customers = []
sales = []
thread_sold = []
date = []

transactions_list.append(customers)
transactions_list.append(sales)
transactions_list.append(thread_sold)
transactions_list.append(date)



for list in transactions_list:
  for data in transactions_clean:
    list.append(data)

But still none of the solutions worked, I even tried to convert it in a list of lists and aply the same method i did in the first example, but I keept geting a message error saying that the index was out of range. Does anyone know how to create a loop that does what I need for this exercise?

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

You could use print to write out what values you’ve got.

For example what is each value in transactions_clean? Is it customers, sales, threads, dates all mixed, or is each entry a group containing all of those?

It’s probably not got very much to do with knowing what to do as much as it has to do with looking at what you’ve got and acting accordingly.

Don’t try random stuff, instead look at what you have and then decide, firmly, what you need to do based on what you see. Then implement that, without compromise.

1 Like

The reason that your index is out of range is because you reset it to zero outside of the for loop. To avoid this error, I would recommend making the following changes:

for transaction in transactions_clean:
index = 0
customers.append(transaction[index])
index += 1
sales.append(transaction[index])
index += 1
thread_sold.append(transaction[index])
index += 1
date.append(transaction[index])

That should do the trick! (with property indentation; it’s a bit difficult to do on my computer at the moment)