Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between {} and [] in python?

Tags:

python

syntax

What is the difference between columnNames = {} and columnNames = [] in python?

How can i iterate each one? using {% for value in columnNames %} OR for idx_o, val_o in enumerate(columnNames):

like image 989
Mithun Sreedharan Avatar asked Mar 08 '11 09:03

Mithun Sreedharan


People also ask

What is the difference between () [] {} in Python?

() is a tuple: An immutable collection of values, usually (but not necessarily) of different types. [] is a list: A mutable collection of values, usually (but not necessarily) of the same type. {} is a dict: Use a dictionary for key value pairs.

What is this {} in Python?

Practical Data Science using PythonAn empty dictionary without any items is written with just two curly braces, like this: {}. Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Why do we use [] in Python?

You use square brackets to create lists for both empty lists and those that have items inside them.

Is list () and [] the same in Python?

In practical terms there's no difference. I'd expect [] to be faster, because it does not involve a global lookup followed by a function call. Other than that, it's the same.


2 Answers

  • columnNames = {} defines an empty dict
  • columnNames = [] defines an empty list

These are fundamentally different types. A dict is an associative array, a list is a standard array with integral indices.

I recommend you consult your reference material to become more familiar with these two very important Python container types.

like image 184
David Heffernan Avatar answered Sep 23 '22 22:09

David Heffernan


In addition to David's answer here is how you usually iterate them:

# iterating over the items of a list
for item in someList:
    print( item )

# iterating over the keys of a dict
for key in someDict:
    print( key, someDict[key] )

# iterating over the key/value pairs of a dict
for ( key, value ) in someDict.items():
    print( key, value )
like image 33
poke Avatar answered Sep 22 '22 22:09

poke