Python Basics #09 – Collections in Python

-->

In this part of the Python Basics tutorial, we will learn about the collections in python. Let’s first understand what is a collection.

What are collections in python?

A collection unlike a sequence is a kind of object which is used to hold data without any deterministic ordering. The order of items may change when an item is added or deleted.

Types of collections in python

There are 2 main types of collections in python

  • Set
  • Dictionary

Let’s see each of these collections in detail below.

Set

A set in python is similar to a set in mathematics. It can not hold duplicate values.

Set can be declared using curly braces ( {} ) or the set() method. Look for both the ways in the example below.

>>> s = {1,2,3,4,5,2,3,1}
>>> s
{1, 2, 3, 4, 5}
>>>
>>> list = [1,2,3,4,5,2,3,1]
>>> s2 = set(list)
>>> s2
{1, 2, 3, 4, 5}
>>>

A set is not indexable (or scriptable) in python. Let’s try to see what happens.

>>> s
{1, 2, 3, 4, 5}
>>> s[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not subscriptable
>>>

A set is mutable. But it cant hold any other mutable item like lists or others sets for example.


>>> s.discard(3)
>>> s
{1, 2, 4, 5}
>>>

Dictionary

Dictionary in python holds data in key value pairs. It is also mutable.

A Dictionary is also declared using curly braces. But, the difference here is that it must contain a key-value pair.

A dictionary can be declared using curly braces ( {} ) or the dict() method. We will look at both these ways in the example below.

>>> d = {'key1':'value1', 'key2':'value2'}
>>> d
{'key1': 'value1', 'key2': 'value2'}
>>>
>>> d2 = dict()
>>> d2['key1'] = 'value1'
>>> d2['key2'] = 'value2'
>>> d2
{'key1': 'value1', 'key2': 'value2'}
>>>

We can access the value of a key in a dict by using the key in place of the index as done in a list.
USAGE: dictName[key] = value

>>> d['key1']
'value1'
>>> d['key2']
'value2'
>>>

Let’s now try to change the value of the ‘key2’ in dict d.

>>> d['key2'] = 'changed value'
>>> d
{'key1': 'value1', 'key2': 'changed value'}
>>>

Back : Python Basics #8 – Sequences

Next : Python Basics #10 – Functions

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: