user2054074
user2054074

Reputation: 41

What is the difference between list / array representation [] and {}?

What is the difference between :

dictionary = []

and

dictionary = {}

assuming dictionary has string contents ?

Upvotes: 1

Views: 150

Answers (2)

shantanoo
shantanoo

Reputation: 3704

On python 2.x

>>> type([])
<type 'list'>
>>> type({})
<type 'dict'>
>>>

On python 3.x

>>> type([])
<class 'list'>
>>> type({})
<class 'dict'>
>>>

Upvotes: 0

mgilson
mgilson

Reputation: 310089

In the first case, you're making a list whereas the other you're making a dict. list objects are sequences whereas dict objects are mappings. Have a look at the python types page.

Basically, lists "map" sequential integers (starting at 0) to some object. In that way, they behave a lot more like a dynamic array in other languages. In fact, Cpython implements them as overallocated arrays in C.

dict map hashable keys to an object. They're implemented using hash tables.


Also note that starting from python2.7, you can use the {} to create sets as well which are another (fundamental) type. Review:

[] #empty list
{} #empty dict
set() #empty set

[1] #list with one element
{'foo':1} #dict with 1 element
{1} #set with 1 element

[1, 2] #list with 2 elements
{'foo':1, 'bar':2} #dict with 2 elements
{1, 2} #set with 2 elements. 

Upvotes: 9

Related Questions