Grieve (grieve) wrote,
Grieve
grieve

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: progamming
Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 0 comments