简体   繁体   中英

Accessing list elements using double square brackets (python)

given a list, such as:

programming_languages = ['Python', 'Perl', 'R', 'Ruby']

What are the rules for using double square brackets []?

What I mean is if I try accessing programming_languages[2][0] or programming_languages[3][0] or programming_languages[-1][-4] for example, I'll get the element 'R'.

Thanks in advance for the help on clearing this up for me!

Edit: For some reason I did not realise the 'R' I get while accessing programming_languages[3][0] or programming_languages[-1][-4] is actually the 1st character of the 4th element in the list, and NOT the 2nd element 'R'. Thanks for the answers below!

The square bracket operator isn't only defined on arrays, but also on strings.

a = programming_languages[1] # a = 'Perl'
print(a[0]) # P, which is the 0th letter of the string
print(a[3]) # l, which is the 3rd letter of the string

programming_languages is an array, so you are accessing each elemnt inside the array by first bracket, eg. : programming_languages[0] which returns 'Python' . noe in python, strings are considers as an array of characters, so the second bracket is picking the character whiting that string, so eg: programming_languages[0][0] returns 'P'

The square bracket syntax, like programming_languages[n] allow you to access the nth element.

programming_languages = ['Python', 'Perl', 'R', 'Ruby']
programming_languages[0] # getting the first element in the list
# Python

When you use double square bracket, it means your element is a list-like object. If the first elements is Python then the first element would be P

>>> programming_languages = ['Python', 'Perl', 'R', 'Ruby']
>>> # getting the first element in the list
>>> programming_languages[0] 
 Python
>>> # getting the first element in the string 'Python'
>>> programming_languages[0][0] 
 P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM