Python: What does the use of [] mean here?

Andrew Hubbs picture Andrew Hubbs · Sep 22, 2010 · Viewed 16.3k times · Source

What is the difference in these two statements in python?

var = foo.bar

and

var = [foo.bar]

I think it is making var into a list containing foo.bar but I am unsure. Also if this is the behavior and foo.bar is already a list what do you get in each case?

For example: if foo.bar = [1, 2] would I get this?

var = foo.bar #[1, 2]

and

var = [foo.bar] #[[1,2]] where [1,2] is the first element in a multidimensional list

Answer

jathanism picture jathanism · Sep 22, 2010

[] is an empty list.

[foo.bar] is creating a new list ([]) with foo.bar as the first item in the list, which can then be referenced by its index:

var = [foo.bar]
var[0] == foo.bar # returns True 

So your guess that your assignment of foo.bar = [1,2] is exactly right.

If you haven't already, I recommend playing around with this kind of thing in the Python interactive interpreter. It makes it pretty easy:

>>> []
[]
>>> foobar = [1,2]
>>> foobar
[1, 2]
>>> [foobar]
[[1, 2]]