#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2004
    Posts
    11
    Rep Power
    0

    simple list manipulation


    i have a nested tuple/list such
    a=[(1,2,3,4,5,6),(1,2,5,3,5,3),(2,4,5,3,4,3)]
    i want to create out of it another list with the elements of the second column for example : b=[2,2,4] . Do you have any idea ?
    i can just print such result but not as a new list


    Nikos
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    List comprehensions to the rescue!

    Code:
    >>> a=[(1,2,3,4,5,6),(1,2,5,3,5,3),(2,4,5,3,4,3)]
    >>> [x[1] for x in a]
    [2, 2, 4]
    There are other ways of doing it, but this is by far the simplest.

    In Python 2.4 you can also use a generator expression to create a generator that will retrieve the results when needed. For a large list this can be much more efficient:

    Code:
    >>> gen = (x[1] for x in a)
    >>> gen.next()
    2
    >>> gen.next()
    2
    >>> gen.next()
    4
    >>> gen.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    StopIteration
    >>>
    Dave - The Developers' Coach
    Last edited by DevCoach; December 5th, 2004 at 06:13 PM.

IMN logo majestic logo threadwatch logo seochat tools logo