Access elements from nested tuples

Tim Chase python.list at tim.thechases.com
Mon Sep 4 23:09:57 CEST 2006


> t = (1, (2, 3))
> 
> I am bit suprised, that I cannot access '3' via:
> t[1].[1] # syntax error
> 
> But t[1].__getitem__(1) works like expected.
> 
> Why is that?

What is "t"?  It's a tuple.  A tuple can be indexed, or you can 
call its __getitem__ method.  Thus, the one-th element of t is either

	t[1]

or

	t.__getitem__(1)

You're asking for the sub-element of that thing just returned. 
Thus, you either need to use

	t[1][1]

or

	t[1]._getitem(1)

or

	t.__getitem__(1)[1]

or

	t.__getitem__(1).__getitem__(1)



Imagine that you used

	x = t[1]

You wouldn't use

	x.[1]

you'd use

	x[1]

or

	x.__getitem__(1)

Same thing.  As simple as search-and-replace of "t[1]" with "x"

-tkc







More information about the Python-list mailing list