[python] 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?

This question is related to python list tuples

The answer is


If you want to use names, try a namedtuple:

from collections import namedtuple

Pair = namedtuple("Pair", ["first", "second"])

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

for pair in pairs:
    print("First = {}, second = {}".format(pair.first, pair.second))

When you say pair[0], that gives you ("a", 1). The thing in parentheses is a tuple, which, like a list, is a type of collection. 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].


You can access the members by their index in the tuple.

lst = [(1,'on'),(2,'onn'),(3,'onnn'),(4,'onnnn'),(5,'onnnnn')]

def unFld(x):

    for i in x:
        print(i[0],' ',i[1])

print(unFld(lst))

Output :

1    on

2    onn

3    onnn

4    onnnn

5    onnnnn

A 2-tuple is a pair. You can access the first and second elements like this:

x = ('a', 1) # make a pair
x[0] # access 'a'
x[1] # access 1

I don't think that you'll like it but I made a pair port for python :) using it is some how similar to c++

pair = Pair
pair.make_pair(value1, value2)

or

pair = Pair(value1, value2)

here's the source code pair_stl_for_python


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to tuples

Append a tuple to a list - what's the difference between two ways? How can I access each element of a pair in a pair list? pop/remove items out of a python tuple Python convert tuple to string django: TypeError: 'tuple' object is not callable Why is there no tuple comprehension in Python? Python add item to the tuple Converting string to tuple without splitting characters Convert tuple to list and back How to form tuple column from two columns in Pandas