Overview of list and set¶
There are 4 types of collections in Python. While list
and set
fundamentally contain homogeneous elements, dict
and tuple
contain heterogeneous elements.* Homogeneous means of same type.
- Examples of collections with homogeneous elements.
- Collection of employees –
list
- Collection of unique employees –
set
- Collection of integers –
list
- Collection of unique integers –
set
- Collection of employees –
- Based up on the requirement we should use appropriate type of collection.
list
- Group of homogenous elements.
- There can be duplicates in the
list
. list
can be created by enclosing elements in[]
– example[1, 2, 3, 4]
.- Empty
list
can be initialized using[]
orlist()
.
set
- Group of homogenous elements
- No duplicates allowed in the
set
. Even if you add same element more than once, such elements will be ignored. set
can be created by enclosing elements in{}
– example{1, 2, 3, 4}
.- Empty
set
can be initialized usingset()
. We cannot initialize empty set using{}
as it will be treated as emptydict
.
list
andset
can be analogous to Table with columns and rows whiledict
andtuple
can be analogous to a row with in a table.list
can hold duplicate values whileset
can only hold unique values.- If you want to have a row with column names then we use
dict
otherwise we usetuple
. - We will deep dive into all types of collections to get better understanding about them.
In [1]:
l = [1, 2, 3, 3, 4, 4]
In [2]:
l
Out[2]:
[1, 2, 3, 3, 4, 4]
In [3]:
l = []
In [4]:
l
Out[4]:
[]
In [5]:
type(l)
Out[5]:
list
In [6]:
l = list()
In [7]:
l
Out[7]:
[]
In [8]:
s = {1, 2, 3, 3, 4, 4}
In [9]:
s
Out[9]:
{1, 2, 3, 4}
In [10]:
type(s)
Out[10]:
set
In [11]:
s = set() # Initializing empty set
In [12]:
s
Out[12]:
set()
In [13]:
s = {} # s will be of type dict
In [14]:
type(s)
Out[14]:
dict