Reputation: 361
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
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
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
Reputation: 2762
l = [('a', 'b'), ('c', 'd')]
first_items = [a for (a, b) in l]
print first_items
Upvotes: 1