3

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

Community
  • 1
  • 1
DevilWAH
  • 2,553
  • 13
  • 41
  • 57

2 Answers2

7

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]
Community
  • 1
  • 1
Andrew Che
  • 928
  • 7
  • 20
5

Use sum:

>>> LED = [[255, 255, 255], [135, 234, 111], [244, 75, 128]]
>>> sum(LED, [])
[255, 255, 255, 135, 234, 111, 244, 75, 128]
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • interesting! the standard way would seem to be the other the list comprehension idea but this is cool. – parsethis Mar 12 '17 at 21:45
  • I timed these both using the Link from Андрей Череваткин answer.Both work but the first method is quite a bit fater than using Sum pi@Laserv3:~/APA102 $ 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 pi@Laserv3:~/APA102 $ 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 pi@Laserv3:~/APA102 $ – DevilWAH Mar 12 '17 at 23:19
  • Please note This is a O(N^2) operation. On each iteration a completely new list is built, keep this in mind when considering performance for huge lists this will be slow – jamylak Mar 13 '17 at 02:18