Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python concatenating Lists [duplicate]

I have an List of list as below.

LED = [[255, 255, 255], [135, 234, 111], [244, 75, 128]]

AS you may have guessed these are Red/Green/Blue values for a number of LED's and I want them in this structure as I can address each member in the code by index. So i can change the value of LED[1] simply by writing new vaules to that item in the list.

However when it comes to writing them out i want a single list not a list of lists. so i have

For x in range (0, NumLED):
        LEDs = LEDs + LED[x]

Which would give

LEDs = [255, 255, 255, 135, 234, 111, 244, 75, 128]

Is there a better way to do this than looping through,for 3 LEDs it fine but for lists of hundreds I want to update the LED strip > 24 times a second, (and there are other things going on in the code) so any efficiency in concatenating this and save a few cycles would be great.

EDIT.

I tested the timing of using the sugested methods

python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'  
100 loops, best of 3: 5.79 msec per loop  
python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'  
1000 loops, best of 3: 308 usec per loop  

So it seems [item for sublist in l for item in sublist] is qutie a bit quicker.

Thanks all for the suggestions.

Aaron

There is a good explication of different methods of doing this with explication and timings in this question

Making a flat list out of list of lists in Python

like image 911
DevilWAH Avatar asked Jan 31 '26 10:01

DevilWAH


2 Answers

I found a truly beautiful solution here

Making a flat list out of list of lists in Python

>>> LED = [[255, 255, 255], [135, 234, 111], [244, 75, 128]]
>>> [item for sublist in LED for item in sublist]
[255, 255, 255, 135, 234, 111, 244, 75, 128]
like image 52
Andrew Che Avatar answered Feb 02 '26 22:02

Andrew Che


Use sum:

>>> LED = [[255, 255, 255], [135, 234, 111], [244, 75, 128]]
>>> sum(LED, [])
[255, 255, 255, 135, 234, 111, 244, 75, 128]
like image 44
Daniel Avatar answered Feb 02 '26 22:02

Daniel