How to select every nth item from a list a list (inspired by my mistake in Thread Shed)

Hello Everyone,

This questions is inspired by a mistake I made in the Thread Shed project. In the project, you are supposed to make a list of lists but instead I made ended up with one long list. I realize where I went wrong in the original project, but it got me wondering if there is a better way to select every 4th item from a list. The solution I came up with works but I feel like I am missing something obvious that would make for a simpler solution than having 3 separate counters and 3 separate for loops.

transactions_clean = ['Edith Mcbride', '$1.21', 'white', '09/15/17', 'Herbert Tran', '$7.29', 'white&blue', '09/15/17', 'Paul Clarke', '$12.52', 'white&blue', '09/15/17', 'Lucille Caldwell', '$5.13', 'white', '09/15/17', 'Eduardo George', '$20.39', 'white&yellow', '09/15/17', 'Danny Mclaughlin', '$30.82', 'purple', '09/15/17']
customers = []
sales = []
thread_sold = []
counter1 = 0
counter2 = 1
counter3 = 2
for i in range(int(len(transactions_clean)/4)):
  counter1 = counter1+4
for i in range(int(len(transactions_clean)/4)):
  counter2 = counter2+4
for i in range(int(len(transactions_clean)/4)):
  counter3 = counter3+4

What would be a better way to think about this problem? I have been trying to come up with a simpler and straightforward way to do this.Thanks for your help!

# x = [ , , , ] of some length

every_4th_one = range(3, len(x), 4)

n = []
for i in every_4th_one:

The advantage of this is that we’re only ever working with integers as indices.

1 Like

Thank you! That makes sense and is much cleaner.

Thank you for your help!

1 Like