-1

I want to write a succinct and elegant code for the following problem:

Assuming that I have a list of tuples:

[(x1,y1), (x2,y2), ....., (xn,yn)].

I want to create a list [y1, y2, ....,yn] without using the loops.

Any help appreciated.

Nabin
  • 11,216
  • 8
  • 63
  • 98
Abhishek Mishra
  • 1,984
  • 1
  • 18
  • 13
  • 1
    Anything that will accomplish this *will* loop somewhere, either in python code or in native code. – roippi Sep 04 '14 at 17:00

3 Answers3

3

You can do this:

>>> x = [(1,2),(3,4),(5,6)]
>>> x2 = [k[1] for k in x]
>>> x2
[2, 4, 6]

The list comprehension does a loop internally, but you didn't have to type the words for or while. Is that what you're looking for?

mtrw
  • 34,200
  • 7
  • 63
  • 71
2

You could use zip to transpose the sequence from "N tuples each of size 2" to "2 tuples each of size N", and then slice off everything but the second result:

seq = [("z", "a"), ("y", "b"), ("x", "c")]
print zip(*seq)[1]

Result:

('a', 'b', 'c')
Kevin
  • 74,910
  • 12
  • 133
  • 166
0

mtrw has the right idea in standard Python. However, if you'd like to make the jump directly to numpy, I highly recommend it. It allows for all sort of indexing:

import numpy as np
x = np.array([(1,2),(3,4),(4,5)])

x[:,1]

Result:

array([2,4,6])

Edit: In addition to this simple indexing, you can loop over the arrays like any list, and has all the same properties plus more. Edit 2: vanilla -> standard

Aku
  • 526
  • 4
  • 17