?

Log in

Previous Entry | Next Entry

List Comprehensions in python

veloso had an interesting python puzzle for me in python. How could you take a tuple in python, such as (1,2,3) and transform it into the tuple (1,1,2,2,3,3)? For the examples below assume orig = (1,2,3)

His original stab as presented to me was follows:
    newTuple = tuple(chain(*(repeat(x, 2) for x in orig)))

I was able to modify as follows:
    newTuple = tuple(chain(*((x, x) for x in orig)))

Which is slightly cleaner, but his coworker had the best solution:
    newTuple = tuple(i for x in orig for i in (x,x))


I am not a big fan of list comprehensions (I think they make the code harder to read), so I came up with the follow:
   def repeatElements(list, count):
      for x in list:
         for y in range(count):
            yield x

   newTuple = tuple(repeatElements(orig, 2))

This has the added benefit of being able to repeat any number of times, but of course requires more lines and a generator function.

Tags:

Latest Month

July 2011
S M T W T F S
     12
3456789
10111213141516
17181920212223
24252627282930
31      
Powered by LiveJournal.com
Designed by yoksel