0

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)

2
  • Are you seeing the bottom version verbatim, or is that just illustrative? Commented Nov 21, 2019 at 0:44
  • Just illustrative Commented Nov 21, 2019 at 0:47

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I've added to my answer with a more detailed explanation

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.