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

K

kath

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....?
['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.
 
K

Kelvie Wong

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:
0

So thus it follows logically that since:
'a'

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


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....?
['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.
 
R

Robert Bauck Hamar

kath said:
Hi,

Can any one please tell me how is the following code is working?
['a','b'] is a list of string
Yes.

and [True] is list of boolean value.

No. It's the subscription operator applied to the list of strings.
a = ['a', 'b']
a[True]
may be clearer.
How is it making effect....?
( said:
['a','b] [True] 'b'
['a','b'] [False] 'a'
['a','b']['some_string' == r'some_string'] 'b'
['a','b']['some_string' == r'somestring']
'a'

<code>
 
K

kath

Hi Kelvie and RBH,

Thanks for your quick reply. That was very much helpful indeed.

regards,
kath.
 

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,434
Messages
2,571,685
Members
48,796
Latest member
Greg L.

Latest Threads

Top