Roozilla
Roozilla

Reputation: 83

What does this syntax mean in Python 3?

I've been seeing this syntax, but I'm not quite sure what it means. It's when two square brackets are next to the name of one list. I'm assuming this does some type of list slicing?

mylist[x][y]
mylist[][]

These are just some examples of what I've seen. (I've used variables x&y to represent an arbitrary number)

Upvotes: 0

Views: 92

Answers (2)

lxop
lxop

Reputation: 8595

The top line just indexes into a list within a list. So for example, you could have

mylist = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
]

value = mylist[1][2]

which will get the value 6.

The bottom line doesn't look like valid Python to me.


EXPLANATION:

Consider that mylist[1] just extracts the second element from mylist (second because of 0-based indexing), which is [4,5,6]. Then adding [2] looks up the third item in that list, which is 6. You could also write

inner_list = mylist[1]
value = inner_list[2]

or

value = (mylist[1]) [2]

which both do the same thing.

Upvotes: 1

tetrisforjeff
tetrisforjeff

Reputation: 97

This notation can be used when the list contains some other lists as elements, which is helpful to represent the matrices. For example:

a=[[1,2,3],[4,5,6],[7,8,9]]
a[0][0] #This gives the number 1.

In this case, a[0] (the first index) chooses the 1st element, which is [1,2,3]. Then the second index (a[0][0]) chooses the first element of the list defined by a[0], thus giving the answer 1.

Upvotes: 1

Related Questions