2

I have a list like

list_a = [(1, 2), (2, 3), (4, 5)]

and now using this list i wanted to find a element which has last value 3 any short method to achieve this? it should return (2,3)

OpenCurious
  • 2,916
  • 5
  • 22
  • 25

3 Answers3

9

For example:

In [1]: list_a = [(1, 2), (2, 3), (4, 5)]

In [2]: next(x for x in list_a if x[1] == 3)
Out[2]: (2, 3)

Note that it returns a single element, not a list of them (seems to be what you are asking). If there are multiple tuples, the first one is returned.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
0
for item in list_a:
    if item[-1] == 3:
        return item

Or, if you might want to return multiple values:

return_list = []
for item in list_a:
    if item[-1] == 3:
        return_list.append(item)
return return_list
cms_mgr
  • 1,977
  • 2
  • 17
  • 31
0

something simple like

for x in list_a: 
    if x[1] == 3: print x
Aditya Sihag
  • 5,057
  • 4
  • 32
  • 43