user3196332
user3196332

Reputation: 361

python - assistance with "nested" lists

My list looks something like this

[('a', 'b'), ('c', 'd')], except bigger

How can I print the first value of each pair? For example, in that example, I'd just like to print 'a' and 'c'.

I should also add, the list is randomly generated so I won't know the contents

Upvotes: 0

Views: 54

Answers (4)

s16h
s16h

Reputation: 4855

my_list = [('a', 'b'), ('c', 'd')]

for a, _ in my_list:
    print a

The fact that we can do for a, _ in my_list is because of Python's tuple unpacking. The _ is the pythonic way of saying we don't care about that variable and we are not going to use it (as opposed to calling it b or something else).

Upvotes: 3

user3286261
user3286261

Reputation: 501

The print statement does not have to depend upon how many elements are in the tuple:

my_list = [('a', 'b'), ('c', 'd')]

for item in my_list:
    print item[0]

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 114098

print list(map(operator.itemgetter(0),my_list))

Upvotes: 0

Grapsus
Grapsus

Reputation: 2762

l = [('a', 'b'), ('c', 'd')]
first_items = [a for (a, b) in l]
print first_items

Upvotes: 1

Related Questions