LazerSharks
LazerSharks

Reputation: 3155

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

For example in python:

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

Upvotes: 2

Views: 5091

Answers (4)

Yunzhi Ma
Yunzhi Ma

Reputation: 672

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.

Upvotes: 2

munk
munk

Reputation: 12983

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'

Upvotes: 2

nair.ashvin
nair.ashvin

Reputation: 801

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

Upvotes: 3

John La Rooy
John La Rooy

Reputation: 304137

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

Upvotes: 2

Related Questions