Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access each element of a pair in a pair list?

I have a list called pairs.

pairs = [("a", 1), ("b", 2), ("c", 3)] 

And I can access elements as:

for x in pairs:     print x 

which gives output like:

('a', 1) ('b', 2) ('c', 3) 

But I want to access each element in each pair, like in c++, if we use pair<string, int> we are able to access, first element and second element by x.first, and x.second.eg.

x = make_pair("a",1) x.first= 'a' x.second= 1 

How can I do the same in python?

like image 417
impossible Avatar asked Mar 19 '14 05:03

impossible


People also ask

How do you access pair elements in Python?

So you can access the first element of that thing by specifying [0] or [1] after its name. So all you have to do to get the first element of the first element of pair is say pair[0][0] . Or if you want the second element of the third element, it's pair[2][1] .

How do you compare pairs in Python?

Compare the n-th items of both tuple (starting with the zero-th index) using the == operator. If both are equal, repeat this step with the next item. For two unequal items, the item that is “less than” makes the tuple, that contains it, also “less than” the other tuple. If all items are equal, both tuples are equal.

What is pair list?

PairList is a Pair Networks, no-frills mailing list service that runs on GNU Mailman software. You can use PairList to set up mailing lists to easily and efficiently send out newsletters or facilitate an email discussion.

How do you print a pair of numbers in Python?

Is there simpler way of printing sequence of number pairs (two numbers) in python3 ? for x in range(0,n): # [0, n-1] print("{} {}". format(x, x*x));


1 Answers

Use tuple unpacking:

>>> pairs = [("a", 1), ("b", 2), ("c", 3)] >>> for a, b in pairs: ...    print a, b ...  a 1 b 2 c 3 

See also: Tuple unpacking in for loops.

like image 61
alecxe Avatar answered Sep 30 '22 08:09

alecxe