What does two sets of list brackets placed together mean in python?

Question:

For example in python:

employees[x][i] = float(employees[x][i])
Asked By: LazerSharks

||

Answers:

The two brackets mean you’re accessing an element in a list of lists (or dictionaries)

So in this example, it might look something like this

In [17]: employees = {'joe': ['100', 0], 'sue': ['200', 0]}
In [18]: x = 'joe'
In [19]: i = 0
In [20]: employees[x][i]
Out[20]: '100'
Answered By: munk

I put in extra parens to show how this is evaluated

(employees[x])[I] = float((employees[x])[i])

and an example

>>> foo = dict(name="Foo", salary=10.00)
>>> bar = dict(name="Bar", salary=12.00)
>>> employees = dict(foo=foo, bar=bar)
>>> employees
{'foo': {'salary': 10.0, 'name': 'Foo'}, 'bar': {'salary': 12.0, 'name': 'Bar'}}
>>> employees['foo']['name']
'Foo'
>>> employees['bar']['salary']
12.0

employees could also be a list (or any other kind of container)

>>> employees = [foo, bar]
>>> employees
[{'salary': 10.0, 'name': 'Foo'}, {'salary': 12.0, 'name': 'Bar'}]
>>> employees[0]['name']
'Foo'
>>> employees[1]['salary']
12.0
Answered By: John La Rooy

Like most languages, it refers to an element in a multidimensional list:

l = [[0,1,2,3], [1,1,1,1]]
l[1] == [0,1,2,3]
l[1][2] == 2
Answered By: nair.ashvin

Syntax meaning of [] in python:

In python, [] operator is used for at least three purposes (maybe incomplete):

  1. define in literal an array, like xx = [0,1,2,3]
  2. array element indexing, like x1 = xx[1], which requires index be integer or evaluated to a integer
  3. dictionary member retrieval, like s = person[‘firstname’] // person = {‘firstname’:’san’, ‘lastname’:’zhang’}, in this case, the index can be anything that a dict tag can be

Thing goes complex when embedding [] in [] or [] next to [], see examples below:

matrix = [[0,1],[2,3]]
e01 = matrix[0][1]

people = [{'fname':'san','lname':'zhang'}, {'fname':'si', 'lname':'li'}]
last1 = people[1]['lname']

[[]] and [][] are reciprocal to each other.

Answered By: Yunzhi Ma
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.