['a', 'b'][True] results 'b' But how?

Kelvie Wong kelvie at ieee.org
Thu Jul 5 09:15:15 CEST 2007


In this case, [True] and [False] are not lists, rather you're
accessing the items of the list with the index True or False, as per
the following example:

>>> a_list = ['a', 'b']
>>> a_list[True]
'b'
>>> a_list[False]
'a'

This happens because the __getitem__ method takes its argument (which
in this case is True or False) and casts it into an integer:

>>> int(True)
1
>>> int(False)
0

So thus it follows logically that since:
>>> a_list[1]
'b'
>>> a_list[0]
'a'

a_list[True] and a_list[False] must be its first and zeroth  indexed
members, respectively.


On 7/4/07, kath <nitte.sudhir at gmail.com> wrote:
> Hi,
>
> Can any one please tell me how is the following code is working?
> ['a','b'] is a list of string, and [True] is list of boolean value.
> How is it making effect....?
> <code Python24>
>
> >>> ['a','b] [True]
> 'b'
> >>> ['a','b'] [False]
> 'a'
> >>> ['a','b']['some_string' == r'some_string']
> 'b'
> >>> ['a','b']['some_string' == r'somestring']
> 'a'
>
> <code>
>
>
> Thanks in advance,
> regards,
> kath.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Kelvie



More information about the Python-list mailing list