0% found this document useful (0 votes)
16 views

PWP Unit 3 notes

The document provides an overview of data structures in Python, focusing on tuples, lists, and dictionaries. It explains the characteristics, operations, and methods associated with each data structure, including their mutability, indexing, and built-in functions. Examples are provided to illustrate how to create, manipulate, and access elements within these structures.

Uploaded by

gangurdekasturi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

PWP Unit 3 notes

The document provides an overview of data structures in Python, focusing on tuples, lists, and dictionaries. It explains the characteristics, operations, and methods associated with each data structure, including their mutability, indexing, and built-in functions. Examples are provided to illustrate how to create, manipulate, and access elements within these structures.

Uploaded by

gangurdekasturi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Unit-III

Data Structures in Python

Tuples: Tuple is a collection of elements and it is similar to the list. But the items of the tuples
are separated by comma and the elements are enclosed in () parenthesis.

Difference between tuple and list


Tuple List
Tuple uses parenthesis List use square brackets
Tuples cannot be changed List can be changed

Examples of tuples:
T1=(10,20,30,40)
T2=(‘a’, ‘b’, ‘c’, ‘d’)
T3=(‘A’,10,20)
T4=(‘aaa’, ‘bbb’, 30,40)
The empty tuple can be created as
T1=()
The tuple index starts at 0.
Example:
>>>t1=(10,20, ‘AAA’, ‘BBB’)
>>>print(t1[0])
10
>>>print(t1[1:3])
(20, ‘AAA’)

Use of tuple(): There is built in function tuple which is used to create the tuple.
>>>t1=tuple()
>>>print(t1)
()
>>>t1=tuple(‘hello’)
>>>print(t1)
(‘h’, ‘e’, ‘l’, ‘l’, ‘o’)

Comparing Tuples: The tuples can be compared using relational operators. Tuples are
compared position by position. The first item of first tuples is compared to the first item of
second tuple; if they are not equal, this is the result of the comparison, and else the second item
is considered, then the third and so on.

For example:
>>>(4,2)<(3.5)
False

>>>(4,2)<(5,5)
True

Tuple Assignments: we can create a tuple by using assignment operator. Multiple assignments
are possible at a time using tuple assignment.
Example:
>>>a,b=10,20
>>>print(a)
10
>>>print(b)
20
Here the left side is a tuple of variables; the right side is a tuple of expressions. Each value is
assigned to its respective variable.
Split Function: we can also separate out the values in the expression in the tuple by using split
function.
>>>student=’AAA,123’
>>>name,roll=student.split(‘,’)
>>>print(name)
AAA
>>>print(roll)
123
Tuples are Immutable: Tuple is said to immutable. That means once created we cannot change
the tuple.
>>>T1=(10,20,30,40)
>>>Print(T1)
(10,20,30,40)
>>>T1[1]=100
TypeError: 'tuple' object does not support item assignment
Hence tuple are immutable.
Updating Tuple: Tuple are immutable. That means –values in the tuple cannot be changed. We
can only extract the values of one tuple to create another tuple.
>>>T1=(10,20,30)
>>>T2=(40,50)
>>>T3=T1+T2
>>>Print(T3)
(10,20,30,40,50)

Deleting Tuple: We can delete a tuple using del statement.


>>>T1=(10,20,30)
>>>del T1
>>>print(T1)
As an output of the above program, the error message will be displayed as T1 gets deleted.
The zip() function: Zip() is a built in function that takes one or more sequences and produce a
list of tuples.
>>>T1=(10,20,30)
>>>mylist=[‘a’, ‘b’, ‘c’, ‘d’]
>>>print(list(zip(T1,mylist)))
[(10, ‘a’),(20,’b’),(30,’c’)]

Lists: It is basically an ordered sequence of some data written using square brackets ([ ]) and
commas (,).
The values in the list are called elements or items.
Example.
T1=[10,20,30,40] #list of integers
T2=[‘aaa’, ‘bbb’, ‘ccc’] #list of strings
T3=[‘a’, 10,20, ‘b’] #Mixed list
T4=[10,20,[‘a’, ‘b’, ‘c’]) #nested list( The list within another list is called nested list.
T5=[] #Empty list (The list that contains no element is called empty list)

List are Mutable: It is possible to change the values of list. If the bracket operator is present on
the left hand side, then that element is identified and the list element is modified accordingly.
>>>a=[‘AAA’, ‘BBB’, ‘CCC’]
>>>a[1]= ‘XXX’
>>>print(a)
[‘AAA’, ‘XXX’, ‘CCC’]

IN Operator: Using the in operator we can check whether particular element belongs to the list
or not.
If the given element is present in the list it returns true otherwise false.
>>>a=[‘AAA’, ‘XXX’, ‘CCC’]
>>> ‘XXX’ in a
True
>>> ‘BBB’ in a
False

Traversing List: For loop is used to traverse the list elements.


Syntax:
for variable in list:
body
Example:
>>>a=[‘a’, ‘b’, ‘c’, ‘d’] #list a is created
>>>for i in a:
>>>print(i)
Output:
a
b
c
d
List traversing using Function:
1) Using the range () function: Using range () function we can access each element of the
list using index of a list.
If we want to increment each element of the list by one, the we must pass index as
argument to for loop.

>>>a=[10,20,30,40]
>>>for i in range(len(a)):
>>>a[i]=a[i]+1
>>>print(a)
[11, 21, 31, 41]

2) Using enumerate () function: We can print both index and item of the list.
a=[10,20,30]
for i in enumerate(a):
print(i)

output:

(0,10)
(1,20)
(2,30)

List Operations: There are two operations that can be performed using operators such as + and
*.
1. Concatenation using +: The two lists can be created and can be joined using + operator.

>>>L1=[10,20,30]
>>>L2=[40,50,60]
>>>L3=L1+L2
>>>print(L3)

Output:

[10,20,30,40,50,60]

2. Repetition using * : The * used to repeat the list for number of times.

>>>[10,20,30]*3

Output:

[10,20,30,10,20,30,10,20,30]

List Slices: The: operator used within the square bracket that it is a list slice and not the index of
the list.
>>>a=[10,20,30,40,50,60]
>>>a[1:4]
[20,30,40]

If we omit the first index then the list is considered from the beginning.
>>>a[:5]
[10,20,30,40,50]
If we omit the last second index then slice goes to end.
>>>a[4:]
[50,60]
If we omit both the first and second index then the list will be displayed from beginning to end.
>>>a[:]
[10,20,30,40,50,60]

List Methods:
1) Append: It adds the element at the end of the list.

>>>a=[10,20,30]
>>>a.append (40)
>>>print(a)

Output:
[10,20,30,40]

>>>b=[‘A’, ‘B’, ‘C’]


>>>b.append (‘D’)
>>>print(b)

Output:
[‘A’, ‘B’, ‘C’, ‘D’]

2. Extend: It takes the list as an argument and appends this list at the end of old list.

>>>a=[10,20,30]
>>>b=[‘a’, ‘b’, ‘c’]
>>>a.extend(b)
>>>print(a)
Output:
[10, 20, 30, ‘a’, ‘b’, ‘c’]

3. Sort: It arranges the elements in increasing order.


>>>a=[‘x’, ‘z’, ‘u’, ‘v’, ‘y’, ‘w’]
>>>a.sort()
>>>print(a)

Output:
[‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’]

Deleting Elements: The deletion of any element from the list is carried out using functions like
pop, remove and del.
POP Function: If we know the index of the element to be deleted then just pass that index as an
argument to pop function.
>>>a=[10,20,30,40]
>>>val=a.pop(1)
>>>print(a)
Output:
[10,30,40]
If we do not provide any argument to the pop function then the last element of the list will be
deleted.
>>>a=[10,20,30,40]
>>>val=a.pop()
>>>print(a)

Output:
[10,20,30]
Remove function: if we know the value of the element to be deleted then the remove function is
used.
>>>a=[10,20,30,40]
>>>a.remove(20)
>>>print(a)

Output:
[10,30,40]

Del Function: It is possible to remove more than one element at a time using del function.
>>>a=[10,20,30,40,50]
>>>del a[2:4]
>>>print(a)

Output:
[10,20,40]

List Functions:
1. len(): This function returns the length of the string.
>>> a=[10,20,30,40,50]
>>> b=len(a)
>>> print(b)
5
2. max(): This function returns maximum element present in the list.
>>> a=[10,20,30,40,50]
>>> b=max(a)
>>> print(b)
50
3. min():This function returns minimum element present in the list.
>>> a=[10,20,30,40,50]
>>> b=max(a)
>>> print(b)
10
4. Sum(): This function returns the sum of all the elements in the list.
>>> a=[10,20,30,40,50]
>>> b=sum(a)
>>> print(b)
150
5. Sort(): This function returns a list which is sorted one.
>>> a=[50,30,20,40,10]
>>> a.sort()
>>> print(a)
[10, 20, 30, 40, 50]

List and Strings:


1. List Function:
String is a sequence of characters and list is sequence of values.
But list of characters is not the string.
We can convert the string to list of characters.

>>> str='hello'
>>> a=list(str)
>>> print(a)
['h', 'e', 'l', 'l', 'o']
2. Split Function: if the strings contains multiple words then we need to use built in function
split to split the words into the list.
>>> a="I Love Python Programming Very much"
>>> b=a.split()
>>> print(b)
['I', 'Love', 'Python', 'Programming', 'Very', 'much']
3. Join Function: It exactly reverse to the split function. It takes the list of strings and
concatenate to form a string.
>>> a=['I', 'Love', 'Python', 'Programming', 'Very', 'much']
>>> ch=(' ')
>>> ch.join(a)
'I Love Python Programming Very much'

List Comprehensions: It is used to create and define new lists using existing lists.
Example: Write a python program to create a list of even numbers from 0 to 10.
even=[]
for i in range(1,11):
if i%2==0:
even.append(i)
print("Even number list is:",even)

output:
Even number list is: [2, 4, 6, 8, 10]
Example: Write a python program to create a list of odd numbers from 0 to 10.
odd=[]
for i in range(1,11):
if i%2!=0:
odd.append(i)
print("Even number list is:",odd)

output:
odd number list is: [1, 3, 5, 7, 9]
Dictionary: dictionary is ordered collection of items. These items are in the form of key- value
pairs.
The dictionary contains the collection of indices called keys and collection of values.
Each key is associated with a single value.
Creating dictionary:

A = {1:'red',2:'blue',3:'yellow'}
Print (A)

>>> a={} #Empty dictionary


>>> print(a)
{}

>>> a={1:'red',2:'blue',3:'yellow'} #Keys as integer.


>>> print(a)
{1: 'red', 2: 'blue', 3: 'yellow'}

>>> a={'name':'sachin',2:89} #Mixed dictionary


>>> print(a)
{'name': 'sachin', 2: 89}

We can also create a dictionary using the word dict().


>>> a=dict({1:'red',2:'blue',3:'yellow'})
>>> print(a)
{1: 'red', 2: 'blue', 3: 'yellow'}

Accessing the elements in the dictionary:


student={'name':'sachin','roll':1}
>>> print(student['name'])
sachin
>>> print(student['roll'])
1
Dictionary Operations:
1. Adding item to dictionary: we can add the item to the dictionary.
>>> a={1:'red',2:'blue',3:'yellow'}
>>> print(a)
{1: 'red', 2: 'blue', 3: 'yellow'}
>>> a[4]='black'
>>> print(a)
{1: 'red', 2: 'blue', 3: 'yellow', 4: 'black'}

2. Remove item from dictionary: For removing an item from the dictionary we use the
keyword del.

>>> a={1: 'red', 2: 'blue', 3: 'yellow', 4: 'black'}


>>> print(a)
{1: 'red', 2: 'blue', 3: 'yellow', 4: 'black'}
>>> del a[2]
>>> print(a)
{1: 'red', 3: 'yellow', 4: 'black'}

3. Updating the value of the dictionary: we can update the value of the dictionary by
directly assigning the value to corresponding key position.
>>> a={1:'red',2:'blue',3:'black',4:'yellow'}
>>> print(a)
{1: 'red', 2: 'blue', 3: 'black', 4: 'yellow'}
>>> a[2]='pink'
>>> print(a)
{1: 'red', 2: 'pink', 3: 'black', 4: 'yellow'}

4. Checking length: the len() function gives the number of pairs in the dictionary.
>>> a={1:'red',2:'blue',3:'black',4:'yellow'}
>>> len(a)
4

Dictionary Methods:
1. The Clear method: This method remove all the items from dictionary.

>>> a={1:'red',2:'blue',3:'black',4:'yellow'}
>>> print(a)
{1: 'red', 2: 'blue', 3: 'black', 4: 'yellow'}
>>> a.clear()
>>> print(a)
{}

2. The copy method: The copy method returns the copy of the dictionary.
>>> a={1:'red',2:'blue',3:'black',4:'yellow'}
>>> print(a)
{1: 'red', 2: 'blue', 3: 'black', 4: 'yellow'}
>>> b=a.copy()
>>> print(b)
{1: 'red', 2: 'blue', 3: 'black', 4: 'yellow'}
3. The fromkey method: It creates a new dictionary from the given sequence of elements
with a value provided by the user.
>>> keys={10,20,30}
>>> values='number'
>>> a=dict.fromkeys(keys,values)
>>> print(a)
{10: 'number', 20: 'number', 30: 'number'}
4. The get method: It returns the value for the specified key if the key is in dictionary.
>>> a={1:'red',2:'blue',3:'black',4:'yellow'}
>>> print(a.get(1))
red
>>> print(a.get(2))
blue
>>> print(a.get(3))
black
>>> print(a.get(4))
yellow
5. The Value Method: It display the list of values present in the dictionary.
>>> a={1:'red',2:'blue',3:'yellow',4:'black'}
>>> print(a.values())
dict_values(['red', 'blue', 'yellow', 'black'])

6. The POP Method: It removes an element from dictionary having the given key.

>>> a={1:'red',2:'blue',3:'yellow',4:'black'}
>>> a.pop(2)
'blue'
>>> print(a)
{1: 'red', 3: 'yellow', 4: 'black'}

Dictionary as set of counters:


Suppose a string is given and we have to find out the frequency of each letter present in
that string. Then for this purpose a dictionary is created for each letter and its frequency in the
key value pair form.
str='johnny-jump'
a=dict()
for i in str:
if i not in a:
a[i]=1
else:
a[i]=a[i]+1
print(a)

output:
{'j': 2, 'o': 1, 'h': 1, 'n': 2, 'y': 1, '-': 1, 'u': 1, 'm': 1, 'p': 1}

Looping and Dictionaries:- For iterating through the dictionary we can use for loop.
The corresponding key and values present in the dictionary can be displayed using for loop.
a={1:'red',2:'blue',3:'yellow',4:'black'}
for i in a:
print(i,a[i])

output:
1 red
2 blue
3 yellow
4 black

Dictionaries and Tuples:


1. Items: using this method, we can create list of tuples.
>>> a={1:'red',2:'blue',3:'yellow',4:'black'}
>>> t1=list(a.items())
>>> print(t1)
[(1, 'red'), (2, 'blue'), (3, 'yellow'), (4, 'black')]

2. Sort: It arrange the elements in sorted order.


>>> a={4:'red',1:'blue',3:'yellow',2:'black'}
>>> t1=list(a.items())
>>> t1.sort()
>>> print(t1)
[(1, 'blue'), (2, 'black'), (3, 'yellow'), (4, 'red')]

Multiple assignment with Dictionaries: To traverse the dictionary items we need to


consider two values at a time and these are key and value.
At a time we can assign both of these values. This is called multiple assignment.
>>> a={1:'red',2:'blue',3:'yellow',4:'black'}
>>> for key,val in list(a.items()):
print(key,val)

Output:
1 red
2 blue
3 yellow
4 black

Sets in Python

A set is an unordered collection of items. Every set element is unique (no


duplicates) and must be immutable (cannot be changed).

However, a set itself is mutable. We can add or remove items from it.

Sets can also be used to perform mathematical set operations like union,
intersection, symmetric difference, etc.

Creating Python Sets


A set is created by placing all the items (elements) inside curly braces {},

separated by comma, or by using the built-in set() function.


It can have any number of items and they may be of different types (integer,
float, tuple, string etc.). But a set cannot have mutable elements like lists, sets
or dictionaries as its elements.

# Different types of sets in Python


# 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}
{1.0, (1, 2, 3), 'Hello'}

Try the following examples as well.

# set cannot have duplicates


# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)

# we can make set from a list


# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)

# set cannot have mutable items


# here [3, 4] is a mutable list
# this will cause an error.

my_set = {1, 2, [3, 4]}

Output

{1, 2, 3, 4}
{1, 2, 3}
Traceback (most recent call last):
File "<string>", line 15, in <module>
my_set = {1, 2, [3, 4]}
TypeError: unhashable type: 'list'
Creating an empty set is a bit tricky.

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.

# Distinguish set and dictionary while creating empty set

# initialize a with {}
a = {}

# check data type of a


print(type(a))

# initialize a with set()


a = set()

# check data type of a


print(type(a))

Output

<class 'dict'>
<class 'set'>

Modifying a set in Python


Sets are mutable. However, since they are unordered, indexing has no
meaning.

We cannot access or change an element of a set using indexing or slicing. Set


data type does not support it.
We can add a 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.

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

# my_set[0]
# if you uncomment the above line
# you will get an error
# TypeError: 'set' object does not support indexing

# 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)

Output

{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
Removing elements from a set
A particular item can be removed from a set using the
methods discard() and remove().
The only difference between the two is that the discard() function leaves a set
unchanged if the element is not present in the set. On the other hand,
the remove() function will raise an error in such a condition (if element is not
present in the set).
The following example will illustrate this.

# Difference between discard() and remove()

# 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
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 "<string>", line 28, in <module>
KeyError: 2

Similarly, we can remove and return an item using the pop() method.
Since set is an unordered data type, there is no way of determining which item
will be popped. It is completely arbitrary.

We can also remove all the items from a set using the clear() method.

# 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


my_set.pop()
print(my_set)

# clear my_set
# Output: set()
my_set.clear()
print(my_set)
print(my_set)

Output

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


H
{'r', 'W', 'o', 'd', 'e'}
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 union() method.

# Set union method


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

# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)

Output

{1, 2, 3, 4, 5, 6, 7, 8}
Try the following examples on Python shell.

# use union function


>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}

# use union function on B


>>> B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}

Set Intersection

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

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

# use & operator


# Output: {4, 5}
print(A & B)

Output

{4, 5}

try the following examples on Python shell.

# use intersection function on A


>>> A.intersection(B)
{4, 5}

# use intersection function on B


>>> B.intersection(A)
{4, 5}

Set Difference
Difference of the set B from set A(A - B) is a set of elements that are only
in A but not in B. Similarly, B - A is a set of elements in B but not in A.
Difference is performed using - operator. Same can be accomplished using
the difference() method.

# Difference of two sets


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

# use - operator on A
# Output: {1, 2, 3}
print(A - B)

Output

{1, 2, 3}

Try the following examples on Python shell.

# use difference function on A


>>> A.difference(B)
{1, 2, 3}

# use - operator on B
>>> B - A
{8, 6, 7}

# use difference function on B


>>> B.difference(A)
{8, 6, 7}
Set Symmetric Difference

Symmetric Difference of A and B is a set of elements in A and B but not in both


(excluding the intersection).
Symmetric difference is performed using ^ operator. Same can be
accomplished using the method symmetric_difference().

# Symmetric difference of two sets


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

# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)

Output

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

Try the following examples on Python shell.


# use symmetric_difference function on A
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}

# use symmetric_difference function on B


>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}

Other Python Set Methods


There are many set methods, some of which we have already used above.
Here is a list of all the methods that are available with the set objects:

Method Description

add() Adds an element to the set

clear() Removes all elements from the set

copy() Returns a copy of the set

difference() Returns the difference of two or more sets as a new set

difference_update() Removes all elements of another set from this set

Removes an element from the set if it is a member. (Do nothing


discard()
if the element is not in set)

intersection() Returns the intersection of two sets as a new set


intersection_update() Updates the set with the intersection of itself and another

isdisjoint() Returns True if two sets have a null intersection

issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

Removes and returns an arbitrary set element. Raises


pop()
KeyError if the set is empty

Removes an element from the set. If the element is not a


remove()
member, raises a KeyError

symmetric_difference() Returns the symmetric difference of two sets as a new set

Updates a set with the symmetric difference of itself and


symmetric_difference_update()
another

union() Returns the union of sets in a new set

update() Updates the set with the union of itself and others

You might also like