You are on page 1of 30

Page 1

UNIT-3 DATA STRUCTURES


LISTS

LIST: Python has a great built-in list type named "list". In Python programming, a list is created by placing all
the items (elements) inside a square bracket [ ], separated by commas

A list is similar to an array that consists of a group of elements or items. Just like an array, a list can store
elements. But, there is one major difference between an array and a list. An array can store only one type of
elements whereas a list can store different types of elements.

A single list can contain strings, integers, as well as objects. Lists can also be used for implementing stacks
and queues. Lists are mutable, i.e., they can be altered once declared.

Create and access elements from a list:


Creating a list is as simple as putting different comma-separated values between square brackets.
Example :
my_list = ['p','r','o','b','e']


We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5 elements
will have index from 0 to 4.

Trying to access an element other that this will raise an IndexError. The index must be an integer. We can't use float
or other types, this will result into TypeError.

Example :
my_list = ['p','r','o','b','e']
print(my_list[0])

print(my_list[2])

print(my_list[4])

# Error! Only integer can be used for indexing


# my_list[4.0]

# Nested List
n_list = ["Happy", [2,0,1,5]]

print(n_list[0][1])

print(n_list[1][3])

output: p
o
e
a
5
Page 2

Negative indexing: Python allows negative indexing for its sequences. The index of -1 refers to the last item,
-2 to the second last item and so on.
Example :
my_list = ['p','r','o','b','e']

# Output: e
print(my_list[-1])

# Output: p
print(my_list[-5])

output: e
p

Slice operator in list:


We can access a range of items in a list by using the slicing operator (colon).
Example :
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])

# elements beginning to
4th print(my_list[:-5])

# elements 6th to end


print(my_list[5:])

# elements beginning to
end print(my_list[:])

output: ['o', 'g', 'r']


['p', 'r', 'o', 'g']
['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']

change or add elements to a list:


List are mutable, meaning, their elements can be changed unlike string or tuple. We can use
assignment operator (=) to change an item or a range of items.
Example :
# mistake values
odd = [2, 4, 6, 8]

# change the 1st item


odd[0] = 1

# Output: [1, 4, 6, 8]
print(odd)
Page 3

# change 2nd to 4th items


odd[1:4] = [3, 5, 7]

# Output: [1, 3, 5, 7]
print(odd)

output: [1, 4, 6, 8]
[1, 3, 5, 7]

We can add one item to a list using append() method or add several items using extend() method.
odd = [1, 3, 5]
odd.append(7)
print(odd)
# Output: [1, 3, 5, 7]
odd.extend([9, 11, 13])
print(odd)
# Output: [1, 3, 5, 7, 9, 11, 13]

We can also use + operator to combine two lists. This is also called concatenation.
The * operator repeats a list for the given number of times.
odd = [1, 3, 5]
print(odd + [9, 7, 5])
# Output: [1, 3, 5, 9, 7, 5]
print(["re"] * 3) #Output:
["re", "re", "re"]

Delete or remove elements from a list:


We can delete one or more items from a list using the keyword del. It can even delete the list entirely.
Example :
my_list = ['p','r','o','b','l','e','m']
del my_list[2]
print(my_list)
del my_list[1:5]
print(my_list)
# delete entire
list del my_list
print(my_list)
Page 4

output: ['p', 'r', 'b', 'l', 'e', 'm']


['p', 'm']

Traceback (most recent call last):


File "<stdin>", line 19, in <module>
print(my_list)
NameError: name 'my_list' is not defined
Page 5
Page 6

P.SRIKANTH DEPARTMENT OF CSE @ MIC www.sristudy.in


Page 7

Functional Programming:
Functional Programming decomposes a problem into a set of functions. The map(),filter(),and reduce()
function It is recommended to use list comprehensions instead of these functions where possible.
Page 8

Tuples
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round
brackets(parentheses) a tuple is similar to a list. The difference between the two is that we cannot change the
elements of a tuple once it is assigned. whereas in a list elements can be changed. The values stored in a tuple
can be any type, and they are indexed by integers.

Advantages of Tuple over List:


If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.

Creating a Tuple:
A tuple is created by placing all the items (elements) inside a parentheses (), separated by comma. The
parentheses are optional but is a good practice to write it. A tuple can have any number of items and they may
be of different types (integer, float, list, string etc.).

Example :
# empty tuple
my_tuple = ()
print(my_tuple)

# tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4)
print(my_tuple)
Page 9

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

# tuple can be created without parentheses also called tuple packing


my_tuple = 3, 4.6, "mic"
print(my_tuple)

# tuple unpacking is also possible


a, b, c = my_tuple
print(a)
print(b)
print(c)

output:
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
(3, 4.6, 'mic')
3
4.6
mic

Accessing Elements in a Tuple:


We can use the index operator [] to access an item in a tuple where the index starts from 0. So, a tuple having
6 elements will have index from 0 to 5. Trying to access an element other that (6, 7,...) will raise an
IndexError.

The index must be an integer, so we cannot use float or other types. This will result into TypeError. Likewise,
nested tuple are accessed using nested indexing, as shown in the example below.

Example :
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0])
print(my_tuple[5])

#print(my_tuple[6]) ------------- # IndexError: list index out of range

#my_tuple[2.0] ---------- # TypeError: list indices must be integers, not float
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(n_tuple[0][3])
print(n_tuple[1][1])

output: p
t
s
4
Page 10

Negative Indexing:
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last
item and so on.
Example :
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[-1])

print(my_tuple[-6])

output: t
p

Slicing:
We can access a range of items in a tuple by using the slicing operator - colon " : ".
Example :
my_tuple = ('p','r','o','g','r','a','m','i','z')

# elements 2nd to 4th


print(my_tuple[1:4])

# elements beginning to 2nd


print(my_tuple[:-7])

# elements 8th to end


print(my_tuple[7:])

# elements beginning to
end print(my_tuple[:])

output: ('r', 'o', 'g')


('p', 'r')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

Changing a Tuple:
This means that elements of a tuple cannot be changed once it has been assigned. But, if the element is itself a
mutable datatype like list, its nested items can be changed. We can also assign a tuple to different values
(reassignment).
Example :
my_tuple = (4, 2, 3, [6, 5])
#my_tuple[1] = 9
# TypeError: 'tuple' object does not support item assignment

my_tuple[3][0] = 9
# but item of mutable (list)element can be changed
print(my_tuple)
Page 11

# tuples can be reassigned


my_tuple = ('p','r','o','g','r','a','m')
print(my_tuple)

output: (4, 2, 3, [9, 5])


('p', 'r', 'o', 'g', 'r', 'a', 'm')

We can use + operator to combine two tuples. This is also called concatenation.
We can also repeat the elements in a tuple for a given number of times using the * operator.

# Concatenation
print((1, 2, 3) + (4, 5, 6))
# Repeat
print(("Repeat",) * 3)

output: (1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')

Deleting a Tuple:
Since tuples are immutable, it is not possible to delete individual elements of a tuple, however, we can
delete the whole tuple itself.
> t = (1, "abc", 3.0)
> del t
> t # If we try to access the tuple after deleting it, python will raise an error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 't' is not defined
Page 12

Python Tuple Methods:


Methods that add items or remove items are not available with tuple. Only the following two methods
are available.

Python Tuple Method

Method Description

count(x) Return the number of items that is equal to x

index(x) Return index of first item that is equal to x

my_tuple = ('a','p','p','l','e',)
print(my_tuple.count('p'))
print(my_tuple.index('p'))
output: 2
1

Sets
A set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable
(which cannot be changed). However, the set itself is mutable. We can add or remove items from it. Sets can
be used to perform mathematical set operations like union, intersection, symmetric difference etc.

create a set: A set is created by placing all the items (elements) inside curly braces {}, separated by comma
or by using the built-in function set(). It can have any number of items and they may be of different types
(integer, float, tuple, string etc.).
Example:
# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes


my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

output: {1, 2, 3}
{'Hello', 1.0, (1, 2, 3)}

Example:
# set do not have duplicates
my_set = {1,2,3,4,3,2}
print(my_set)
# Output: {1, 2, 3, 4}
Page 13

Creating an empty set: Empty curly braces {} will make an empty dictionary in Python. To make a set
without any elements we use the set() function without any argument.
Example:
a = {}
# check data type of a
print(type(a))

a = set()
# check data type of a
print(type(a))

output: <class 'dict'>


<class 'set'>

change a set in Python:


Sets are mutable. But since they are unordered, indexing have no meaning. We cannot access or change an
element of set using indexing or slicing. Set does not support it. We can add single element using the add()
method and multiple elements using the update() method. The update() method can take tuples, lists, strings or
other sets as its argument. In all cases, duplicates are avoided.

Example:
# initialize my_set
my_set = {1,3}
print(my_set)

# if you uncomment line 9,


# you will get an error
# TypeError: 'set' object does not support indexing

#my_set[0] ---------- line9

# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)

# add multiple elements


# Output: {1, 2, 3, 4}
my_set.update([2,3,4])
print(my_set)

# add list and set


# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4,5],
{1,6,8}) print(my_set)
Page 14

output: {1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}

Remove elements from a set:


A particular item can be removed from set using methods, discard() and remove(). The only difference
between the two is that, while using discard() if the item does not exist in the set, it remains unchanged. But
remove() will raise an error in such condition.
Example:
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)

# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)

# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)

# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)

# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError: 2
my_set.remove(2)

output: {1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
Traceback (most recent call last):
File "<stdin>", line 27, in <module>
my_set.remove(2)
KeyError: 2

Similarly, we can remove and return an item using the pop() method. Set being unordered, there is no way
of determining which item will be popped. It is completely arbitrary. We can also remove all items from a
set using clear().
Page 15

Example:
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)

# pop an element
# Output: random element
print(my_set.pop())

# pop another element


# Output: random element
my_set.pop()
print(my_set)

# clear my_set
my_set.clear()
print(my_set)

output: {'r', 'W', 'H', 'e', 'o', 'l', 'd'}


r
{'H', 'e', 'o', 'l', 'd'}
set()

Python Set Operations:


Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric
difference. We can do this with operators or methods.

Let us consider the following two sets for the following operations.
> A = {1, 2, 3, 4, 5}
> B = {4, 5, 6, 7, 8}

Set Union Union of A and B is a set of all elements from both sets. Union is performed using | operator. Same
can be accomplished using the method union().

Example:

# initialize A and B and c


A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
c = {10,20,30,40}
Page 16

print(A | B)
A.union(c)

Output: {1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 10, 20, 30, 40}

Set Intersection:
Intersection of A and B is a set of elements that are common in both sets. Intersection is performed using &
operator. Same can be accomplished using the method intersection().

Example:

# initialize A and B and c


A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
c = {2,3,10,20}
# use & operator
print(A & B)
A.intersection(c)

Output: {4, 5}
{2, 3}

Set Difference:
Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly, B - A is a set of
element in B but not in A.

Difference is performed using - operator. Same can be accomplished using the method difference().

Example:

# initialize A and B
A = {1, 2, 3, 4, 5} B
= {4, 5, 6, 7, 8}

P.SRIKANTH DEPARTMENT OF CSE @ MIC www.sristudy.in


Page 17

# use - operator on
A print(A - B)
print(B - A)
A.difference(B)

Output: {1, 2, 3}
{8, 6, 7}
{1, 2, 3}

Set Symmetric Difference:


Symmetric Difference of A and B is a set of elements in both A and B except those that are common in both.
Symmetric difference is performed using ^ operator. Same can be accomplished using the method
symmetric_difference().

Example:
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator print(A ^
B)
A.symmetric_difference(B)

Output: {1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}
Page 18
Page 19

Dictionaries
A real-life dictionary holds words and their meanings. As you can imagine, likewise, Python dictionary is
an unordered collection of items. While other compound data types have only value as an element, a
dictionary holds key-value pairs.

create a dictionary:
Creating a dictionary is as simple as placing items inside curly braces {} separated by comma. An item has a
key and the corresponding value expressed as a pair, key: value. While values can be of any data type and can
repeat, keys must be of immutable type (string, tuple with immutable elements) and must be unique.
# empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a


pair my_dict = dict([(1,'apple'), (2,'ball')])
As you can see above, we can also create a dictionary using the built-in function dict().
Page 20

Access elements from a dictionary:


While indexing is used with other container types to access values, dictionary uses keys. Key can be used
either inside square brackets or with the get() method. The difference while using get() is that it returns None
instead of KeyError, if the key is not found.
Example:
my_dict = {'name':'Srikanth', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error


# my_dict.get('address')
my_dict['address']

output: Srikanth
26
Traceback (most recent call last):
File "<stdin>", line 11, in <module>
my_dict['address']
KeyError: 'address'

Change or add elements in a dictionary:


Dictionary are mutable. We can add new items or change the value of existing items using assignment
operator. If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.
Example:
my_dict = {'name':'Srikanth', 'age': 26}
# update value
my_dict['age'] =
27 print(my_dict)
#Output: {'age': 27, 'name': 'Srikanth'}

# add item
my_dict['address'] = 'Vijayawada'
print(my_dict)

output: {'name': 'Srikanth', 'age': 27}


{'address': 'Vijayawada', 'name': 'Srikanth', 'age': 27}

Delete or remove elements from a dictionary:


We can remove a particular item in a dictionary by using the method pop(). This method removes as item with
the provided key and returns the value. The method, popitem() can be used to remove and return an arbitrary
item (key, value) form the dictionary. All the items can be removed at once using the clear() method. We can
also use the del keyword to remove individual items or the entire dictionary itself.
Page 21

Example:
# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}

# remove a particular item


# Output: 16
print(squares.pop(4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25}


print(squares)

# remove an arbitrary item


# Output: (1, 1)
print(squares.popitem())

# Output: {2: 4, 3: 9, 5: 25}


print(squares)

# delete a particular item


del squares[5]

# Output: {2: 4, 3: 9}
print(squares)

# remove all items


squares.clear()

# Output: {}
print(squares)

# delete the dictionary itself


del squares

# Throws Error
print(squares)

output: 16
{1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9}
{}

Traceback (most recent call last):


File "<stdin>", line 34, in <module>
print(squares)
NameError: name 'squares' is not defined
Page 22

Dictionary in Membership Test


Example:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

# Output: True
print(1 in squares)

# Output: True print(2


not in squares)

# membership tests for key only not value


# Output: False
print(49 in squares)

output: True
True
False

Iterating Through a Dictionary:


Using a for loop we can iterate though each key in a dictionary.
Example:

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}


for i in squares:
print(squares[i])

output: 1
9
81
25
49
Page 23
Page 24

Sequences
A sequence is a group of items with a deterministic ordering. The order in which we put them in is the order
in which we get an item out from them. Python offers six types of sequences.

Strings:
A string is a group of characters. Computers do not deal with characters, they deal with numbers (binary). Even
though you may see characters on your screen, internally it is stored and manipulated as a combination of 0's
and 1's.

This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and
Unicode are some of the popular encoding used.

In Python, string is a sequence of Unicode character. A string is a sequence of characters. We can use a pair of
single or double quotes. And like we’ve always said, Python is dynamically-typed. Every string object is of the
type ‘str’.

Create a string:
Strings can be created by enclosing characters inside a single quote or double quotes. Even triple quotes can be
used in Python but generally used to represent multiline strings and docstrings.
Example:
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
Page 25

print(my_string)

# triple quotes string can extend multiple lines


my_string = """Hello, welcome to
the world of
Python""" print(my_string)

output: Hello
Hello
Hello
Hello, welcome to
the world of Python

Access characters in a string:


We can access individual characters using indexing and a range of characters using slicing. Index starts from
0. Trying to access a character out of index range will raise an IndexError. The index must be an integer. We
can't use float or other types, this will result into TypeError.

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last
item and so on. We can access a range of items in a string by using the slicing operator (colon).
Example:

str = 'programiz'
print('str = ', str)

#first character
print('str[0] = ', str[0])

#last character
print('str[-1] = ', str[-1])

#slicing 2nd to 5th character


print('str[1:5] = ', str[1:5])

#slicing 6th to 2nd last character


print('str[5:-2] = ', str[5:-2])

output: str = programiz


str[0] = p
str[-1] = z
str[1:5] = rogr
str[5:-2] = am

if we try to access index out of the range or use decimal number, we will get errors.
# index must be in range
>>>srikanth="welcome"
>>> srikanth[10]
IndexError: string index out of range
Page 26

# index must be an integer


>>> sri[1.5]
...
TypeError: string indices must be integers

Change or delete a string:


Strings are immutable. This means that elements of a string cannot be changed once it has been assigned. We
can simply reassign different strings to the same name.
> my_string = 'programiz'
> my_string[5] = 'a'
...
TypeError: 'str' object does not support item assignment
> my_string = 'Python'
> my_string
'Python'

We cannot delete or remove characters from a string. But deleting the string entirely is possible using
the keyword del.
> del my_string[1]
...
TypeError: 'str' object doesn't support item deletion
> del my_string
> my_string
...
NameError: name 'my_string' is not defined

Iterating Through String:


Using for loop we can iterate through a string. Here is an example to count the number of 'l' in a string.

Example:
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')

output: 3 letters found

Bytes Sequences:
The function bytes() returns an immutable bytes object.
> a=bytearray(2)
> a
Page 27

bytearray(b'\x00\x00')

> a=bytearray(5)
> a
bytearray(b'\x00\x00\x00\x00\x00')

a[4]=3
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
a[4]=3

Bytes Arrays:
A bytesarray object is like a bytes object, but it is mutable. It returns an array of the given byte size.
> a=bytearray(5)
> a
bytearray(b'\x00\x00\x00\x00\x00')

> bytearray([1,2,3,4])
bytearray(b'\x01\x02\x03\x04')

> bytearray([1,2,3,4,5])
bytearray(b'\x01\x02\x03\x04\x05')

> a[4]=3
> a
bytearray(b'\x00\x00\x00\x00\x03')

Operations on Sequences:
1. Concatenation
2. Membership
3. Python Slice
Functions on Sequences:
1. len()
2. min() and max()
Methods on Sequences:
1. Python index()
This method returns the index of the first occurrence of a value.
> 'banana'.index('n')
>>>2
2. Python count()
count() returns the number of occurrences of a value in a sequence.
> 'banana'.count('na')
>>>2
Page 28

Comprehensions
Comprehensions are constructs that allow sequences to be built from other sequences. Python 2.0 introduced
list comprehensions and Python 3.0 comes with dictionary and set comprehensions.

List Comprehensions:
A list comprehension consists of the following parts:
 An Input Sequence.
 A Variable representing members of the input sequence.
 An Optional Predicate expression.
 An Output Expression producing elements of the output list from members of the Input Sequence
that satisfy the predicate.
Syntax: {expression(variable) for variable in input_set [predicate]

Ex:

[x for x in 'MATHEMATICS' if x in ['A','E','I','O','U']]

Ex:
> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Some of basic examples:


1. { x^2: x is a natural number less than 10 }
>>> [x**2 for x in range(1,10)]
[1, 4, 9, 16, 25, 36, 49, 64, 81]

2.{ x: x is a whole number less than 20, x is even }


> [x for x in range(1,20) if x
%2==0 ] [2, 4, 6, 8, 10, 12, 14, 16, 18]

3.{ x: x is an alphabet in word ‘MATHEMATICS’, x is a vowel }


> [x for x in 'MATHEMATICS' if x in
['A','E','I','O','U']] ['A', 'E', 'A', 'I']
Page 29

Using conditions in list comprehensions:

list_a = [1, 2, 3, 4]
list_b = [2, 3, 4, 5]
common_num = []
for a in list_a:
for b in list_b:
if a == b:
common_num.append(a)
print(common_num)

Output [2, 3, 4]

Find common numbers from two list using list comprehension:


> list_a = [1, 2, 3, 4]
> list_b = [2, 3, 4, 5]
> common_num = [a for a in list_a for b in list_b if a == b]
> print(common_num)
Output: [2, 3, 4]

List comprehensions can also be used to iterate over strings:


> list_a = ["Hello", "World", "In", "SRIKANTH"]
> small_list_a = [str.lower() for str in list_a]
> print(small_list_a)
output: ['hello', 'world', 'in', 'srikanth']

List comprehensions can be used to produce list of list :


> list_a = [1, 2, 3]
> square_cube_list = [ [a**2, a**3] for a in list_a]
> Print(square_cube_list)
output: [[1, 1], [4, 8], [9, 27]]

Set Comprehension
A set comprehension is similar to a list comprehension, but returns a set and not a list. Syntactically, we use
curly brackets instead of square brackets to create a set.
Example 1
> {s for s in [1, 2, 1, 0]}
set([0, 1, 2])
> {s**2 for s in [1, 2, 1,
0]} set([0, 1, 4])
> {s**2 for s in range(10)}
set([0, 1, 4, 9, 16, 25, 36, 49, 64, 81])
Page 30

Example 2
> {(m, n) for n in range(2) for m in range(3,
5)} set([(3, 0), (3, 1), (4, 0), (4, 1)])

Example 3
generate a set of all of the prime numbers that are less than 100.
r= {x for x in range(2, 101)
if not any(x % y == 0 for y in range(2, x))}
output:
{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}

Example 4
> s = { x for x in range(10) }
> s
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

create set from dictionary (keys)


> dt = {1: 10, 2: 20, 3: 30}
> dt
{1: 10, 2: 20, 3: 30}
> type(dt)
<type 'dict'>
> s = set(dt)
> s
set([1, 2, 3])

Dictionary Comprehension:
Dictionary is an unordered collection of items. , a dictionary holds key-value pairs. Creating a dictionary is as
simple as placing items inside curly braces {} separated by comma.
A dictionary comprehension takes the form {key: value for (key, value) in iterable}

Python code to demonstrate dictionary comprehension


# Lists to represent keys and values
keys = ['a','b','c','d','e']
values = [1,2,3,4,5]

# but this line shows dict comprehension


here myDict = { k:v for (k,v) in zip(keys,
values)} print (myDict)
# We can use below too
myDict = dict(zip(keys, values))
print (myDict)

output: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}


{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

You might also like