-1

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!

Juvi
  • 11
  • 3
  • 1
    This might help shed light: https://stackoverflow.com/questions/509211/understanding-slice-notation –  Mar 19 '22 at 17:35
  • Does this answer your question? [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – Abhyuday Vaish Mar 19 '22 at 18:03

3 Answers3

1

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
QWERTYL
  • 1,355
  • 1
  • 7
  • 11
0

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 e.g : programming_languages[0][0] returns 'P'

eshirvana
  • 23,227
  • 3
  • 22
  • 38
  • 2
    Thanks, I just realised that the 'R' I get isnt the 3rd element but actually the 4th element's first character. – Juvi Mar 19 '22 at 17:36
0

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
Ivan Kwong
  • 381
  • 1
  • 6