comsfollower comsfollower - 10 days ago 5
Python Question

Accessing An Element In a List of Tuples

I am trying to access a specific member of a list of tuples in python, for instance I want to get the

fourth
element in the following
tuple
in the list. How do I do that ?

[(1, u'2016-11-30 01:57:42', u'X1', u'd1', u'CHECKING', 100000.0)]


This list is obtained from a database and therefore the whole code looks like this:

accounts = cur.fetchall()
logins = cur2.fetchall()
l = accounts
l1 = l[0][4]
print l1


When I do this, I get the following error:

l1 = l[0][4]
IndexError: list index out of range

Answer

Just use integers to access each index until you arrive at the desired element:

>>> l = [(1, u'2016-11-30 01:57:42', u'X1', u'd1', u'CHECKING', 100000.0)]
>>> l[0][3]
'd1'