3

I need to plot a lot of data samples, each stored in a list of integers. I want to create a list from a lot of concatenated lists, in order to plot it with enumerate(big_list) in order to get a fixed-offset x coordinate. My current code is:

biglist = []
for n in xrange(number_of_lists):
    biglist.extend(recordings[n][chosen_channel])
for x,y in enumerate(biglist):
    print x,y

Notes: number_of_lists and chosen_channel are integer parameters defined elsewhere, and print x,y is for example (actually there are other statements to plot the points.

My question is: is there a better way, for example, list comprehensions or other operation, to achieve the same result (merged list) without the loop and the pre-declared empty list?

Thanks

2
  • I have no idea what you're trying to accomplish Commented Feb 25, 2011 at 5:06
  • @ Falmarri: the code I made seems non-pythonic, so I am looking for a way to avoid the typical empty-list declaration followed by a loop to fill the list one element at a time. Commented Feb 25, 2011 at 5:30

2 Answers 2

4
import itertools
for x,y in enumerate(itertools.chain(*(recordings[n][chosen_channel] for n in xrange(number_of_lists))):
    print x,y

You can think of itertools.chain() as managing an iterator over the individual lists. It remembers which list and where in the list you are. This saves you all memory you would need to create the big list.

Sign up to request clarification or add additional context in comments.

2 Comments

The answer worked, and was what I asked for, indeed. In the other hand, it seem so verbose... But I could not figure out anything better (except using numpy.ndarray for my recordings, so I could just slice things right through...). Many thanks! (my current code incorporated your one-liner ;o)
If you don't like the one line version you can split it up, big_iter = itertools.chain(*(recordings[n][chosen_channel] for n in xrange(number_of_lists)), for x,y in enumerate(big_iter).
3
>>> import itertools
>>> l1 = [2,3,4,5]
>>> l2=[9,8,7]
>>> itertools.chain(l1,l2)
<itertools.chain object at 0x100429f90>
>>> list(itertools.chain(l1,l2))
[2, 3, 4, 5, 9, 8, 7]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.