StephenHiggins - 2 years ago 103
Python Question

select first nth list items within a for loop

What I have at the moment is the below loop which lights each led on a strand of 24 in turn.

``````while True:
for i in range(24):
pixels = [ (0,0,0) ] * numLEDs
pixels[i] = (100, 100, 100)
client.put_pixels(pixels)
time.sleep(0.02)
``````

What I would like to have is that the previously lit leds stay on for each iteration. So the number of lit leds increases by one each time round.

I assumed I could simply select from the start of the list to the i'th item as below.
However this returns a "TypeError: 'int' object is not iterable".

I'm not really clear why this doesn't work.

``````while True:
for i in range(24):
pixels = [ (0,0,0) ] * numLEDs
pixels[:i] = (100, 100, 100)
client.put_pixels(pixels)
time.sleep(0.02)
``````

While I've got your attention, is there a better way to time these loops other than using time.sleep()? Although I am using threading, the sleeps still cause some delays when the led patterns change.

In your first example, the loop turns off the LEDs by setting them to (0,0,0). Instead, why not use this:

``````while True:
for i in range(24):
pixels = [ (100,100,100) ] * (i) + [ (0,0,0) ] * (numLEDs - i)
client.put_pixels(pixels)
time.sleep(0.02)
``````

This sets the first `i` elements of the list to (100,100,100) then the remaining to be (0,0,0).

If i = 5 and numLEDs = 15, you will get this output:

``````[(100, 100, 100), (100, 100, 100), (100, 100, 100), (100, 100, 100), (100, 100, 100), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)]
``````

As you can see, this will leave the others on.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download