3

I have a list of tuples, called list_out. I want to access values of the 2nd column in the list(i want acsses to '313','321'and '365'). list_out is following:

list_out = [('2240', '313', {'Sign': 1}),
            ('2240', '321', {'Sign': 1}), 
            ('2240', '365', {'Sign': -1})]

I used :

print (list_out[0])

out:

('2240', '313', {'Sign': 1})

then i used:

print (list_out[0][1])

out:

313

above code, return value of 2nd columns in one row in the list(only '313'). I want access to the value of 2nd column in all row. Please suggest me a way to solve this problem.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
mina
  • 153
  • 6
  • 18

3 Answers3

5

Try this:

print(list(zip(*list_out))[1])

Output:

('313', '321', '365')

OR:

print([i[1] for i in list_out])

Output:

['313', '321', '365']
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
2
list_out = [('2240', '313', {'Sign': 1}), ('2240', '321', {'Sign': 1}), 
('2240', '365', {'Sign': -1})]
column2=[j for _,j,_ in list_out]

output

['313', '321', '365']
vishalk
  • 182
  • 2
  • 10
2

Using operator.itemgetter:

from operator import itemgetter

res = list(map(itemgetter(1), list_out))

# ['313', '321', '365']

Or via sequence unpacking:

_, res, _ = zip(*list_out)

print(res)

# ('313', '321', '365')

If you do not wish to unpack non-required columns:

from itertools import islice

res = next(islice(zip(*L), 1, None))
jpp
  • 159,742
  • 34
  • 281
  • 339