-1

If i am getting data in the following format:

[(1, 2), (3, 8)]

I understand that this is basically a list of pair tuples, I basically was thinking what is the most effective way of getting the first value of each tuple. So for the above case I would want to get value [1,3]

3 Answers3

0

Python's list comprehension should do the trick and tuples can be accessed using indices just like lists.

>>> l = [(1, 2), (3, 8)]
>>> [x[0] for x in l]
[1, 3]
nehem
  • 12,775
  • 6
  • 58
  • 84
0

Use a list comprehension:

list = [ x[0] for x in values ]

Where values is your list of elements

alebian
  • 786
  • 5
  • 17
0

In your example, to get [1,3] from [(1, 2), (3, 8)]:

>>> a = [(1, 2), (3, 8)]
>>> print [a[0][0], a[1][0]]
[1, 3]

From that, the pattern will be:

>>> [b[0] for b in a]
[1, 3]
MrHanachoo
  • 109
  • 1
  • 6