Access elements from nested tuples

G

Georg Sauthoff

Hi,

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?

Regards
Georg Sauthoff
 
T

Tim Chase

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
 
J

jss

Hi Georg!

In [1]: 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.

In [2]: k=t[1]

In [3]: k[1]
Out[3]: 3

In [4]: t[1][1]
Out[4]: 3

In [5]: k.__getitem__(1)
Out[5]: 3

In [6]: k.[1]
------------------------------------------------------------
File "<ipython console>", line 1
k.[1]
^
SyntaxError: invalid syntax

Note that:
In [7]: type(t[1])
Out[7]: <type 'tuple'>
just as t.

hth,
jss
 
G

Georg Sauthoff

Hi,

[nested tuples]

thanks - I should not post before 8 am or 10 pm ...

Regards
Georg Sauthoff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top