0% found this document useful (0 votes)
24 views23 pages

CH3 PWP Updated

Uploaded by

deshmukhayaan81
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)
24 views23 pages

CH3 PWP Updated

Uploaded by

deshmukhayaan81
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/ 23

Chapter 3: Data Structures in Python (marks=14)

Defining lists, accessing values in list, deleting values in list, updating lists.

Basic List Operations, Built — in List functions

Accessing values in Tuples, deleting values in Tuples, and updating Tuples.

Basic Tuple operations. Built — in Tuple functions

Accessing values in Set, deleting values in Set and updating Sets.

Basic Set operations. Built in Set functions

Accessing values in Dictionary, deleting values in Dictionary and updating Dictionary.


Basic Dictionary operations.
Built — in Dictionaries functions
List
List is a collection of comma-separated values (items) between square brackets.

Defining a List
Creating a list is as simple as putting different comma-separated values between square
brackets. For example

list1 = ['PWP', 'MAD', 6, 20]


list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

List indexing in python

Subject = “Python”

Left --> 0 1 2 3 4 5

P y t h o n

Right --> -6 -5 -4 -3 -2 -1

Accessing Values in Lists


To access values in lists, use the square brackets for slicing along with the index to obtain
value available at that index.

For example-
list1 = ['PWP', 'MAD', 6, 20, 'MAN', 'WBP']
print(list1[2]) #accessing single element from left side of
index 2

print(list1[2:5]) #first 5 elements from left side selected


but we accessing from index 2

print(list1[3:]) #All elements selected but we accessing from


index 3

print(list1[:3]) #3 elements selected accessing from index 0

print(list1[-2]) #accessing single element from right side of


index 2
print(list1[-4:3]) #first 3 elements from left side selected but
we can accessing from index -4.

OUTPUT
6
[6, 20, 'MAN']
[20, 'MAN', 'WBP']
['PWP', 'MAD', 6]
MAN
[6]

Deleting Values in Lists


To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting. You can use the remove() method if you do not know exactly
which items to delete.

For example-
list1 = ['PWP', 'MAD', 6, 20, 'MAN', 'WBP']
del(list1[2]) #deleting single element from left side of index 2

list1 = ['PWP', 'MAD', 6, 20, 'MAN', 'WBP']


del(list1[2:5]) #first 5 elements from left side selected
but from index 2 till fifth will be remove.

list1 = ['PWP', 'MAD', 6, 20, 'MAN', 'WBP']


del(list1[3:]) #All elements selected, but from index 3
till end will be removed from list1

list1 = ['PWP', 'MAD', 6, 20, 'MAN', 'WBP']


del(list1[:3]) #first 3 will be removed

list1 = ['PWP', 'MAD', 6, 20, 'MAN', 'WBP']


del(list1[-2]) #deleting single element from right side of
index 2

list1 = ['PWP', 'MAD', 6, 20, 'MAN', 'WBP']


del(list1[-4:3]) #first 5 elements from left side selected but
from index -4 till fifth element will
remove

list1 = ['PWP', 'MAD', 6, 20, 'MAN', 'WBP']


del(list1[:]) #All elements will be removed from list1

Updating Lists
We can update single or multiple elements of lists by giving the slice on the left-hand side of
the assignment operator, and can add elements in a list with the append() method.

For example-

Single element update


list1 = ['PWP', 'MAD', 6, 20, 'MAN', 'WBP']
list1[2]= 'CPP' #current index 2 element i.e. 6 will be
updated as 'CPP'
print(list1)

Multiple element update


list1[2:4]=['ETE','ADBMS']
print(list1)
List class methods
append ()

The append () method appends an element to the end of the list.

list.append(element)

a = ["apple", "banana", "cherry"]

b = ["Ford", "BMW", "Volvo"]

a.append(b)

print(a)

Output

extend ()

The extend () method appends an multiple elements to the end of the list.

list.extend(iterable)

a = ["apple", "banana", "cherry"]

b = ["Ford", "BMW", "Volvo"]

a.extend(b)

print(a)

Output

clear ()

The clear() method removes all the elements from a list.

list.clear()

a = ["a", "b", "c"]


a.clear()
print(a)
Output
copy ()

The copy() method returns a copy of the specified list.


list.copy()

L = ["a", "b", "c"]

L2 = L.copy()

print(L2)

Output

count ()

The count() method returns the number of elements with the specified element.

list.count(element)

L = ["a", "b", "c", "c", "a", "c"]

cnt = L.count("c")

print(cnt)

Output

index ()

The index() method returns the position at the first occurrence of the specified
element.
The index() method only returns the first occurrence of the value.

list.count(element)

L = [4, 55, 64, 32, 16, 32]

x = L.index(64)

print(x)

Output
insert ()

The insert() method inserts the specified value at the specified position.

Syntax:
list.insert(position, element)

Exmaple:

L = [4, 55, 64, 32, 16, 32]

L.insert(3,68)

print(L)

Output

[4, 55, 64, 68, 32, 16, 32]

pop ()

The pop() method removes the element at the specified position.


Or if position is not passed as argument by default value is -1, means last element
will be popped.
If specified position or index not available in list then Index_Error will be generated.

Syntax:
E=list.pop(position)

Exmaple:

L = [4, 55, 64, 32, 16, 32]

E=L.pop(3)

print(E)

print(L)

Output

32

[4, 55, 64, 68, 16, 32]


remove ()

The remove() method removes the first occurrence of the element with the specified
value.

If element with specified value not available in list then Value_Error will be
generated.

Syntax:
list.remove(position)

Exmaple:

L = [4, 55, 64, 32, 16, 32]

L.remove(55)

print(L)

Output

[4, 64, 32, 68, 16, 32]

reverse ()

The reverse() method reverses the sorting order of the elements.

Syntax:
list.reverse()

Exmaple:

L = [4, 55, 64, 32, 16, 32]

L.reverse()

print(L)

Output

[32, 16, 32, 64, 55, 4]


sort ()

o The sort() method sorts the list ascending or descending order, by default
sorting is done in ascending order.
o To sort in descending order use first argument i.e. reverse make its value to
True.
o You can also make a function to decide the sorting criteria(s).
Syntax:
list.sort(reverse=True/False,key=myfunc)

Exmaple:

To sort given list in descending order as length of elements.

def myfunc(e1):

return len(e1)

L=['MECH','COMPUTER','CIVIL','ROBOTICS','CIVIL1']

L.sort(reverse=True,key=myfunc)

print(L)

Output

['COMPUTER', 'ROBOTICS', 'CIVIL1', 'CIVIL', 'MECH']

TUPLE
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences
between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses,
whereas lists use square brackets.

Creating a Tuple
Creating a tuple is as simple as putting different comma separated values. Optionally you can put these
comma-separated values between parentheses also. Like string indices, tuple indices start at 0 and they
can be sliced, concatenated, and so on.

Example
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

The empty tuple is written as two parentheses containing nothing


tup1 = ();

To write a tuple containing a single value you have to include a comma, even though there is only one
value.
tup1 = (50,);
Accessing Values in Tuples
To access values in tuple, use the square brackets for slicing along with the index or indices to

Obtain value available at that index.

Example:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print(tup1[0]);
print(tup2[1:5]);

Output:
physics
[2, 3, 4, 5]

Updating Tuples: Tuples are immutable which means you cannot update or change
the values of tuple elements. You are able to take portions of existing tuples to create

new tuples.

Example:
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print(tup3);

Output:
(12, 34.56, 'abc', 'xyz')

Delete Tuple Elements:


Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting
together another tuple with the undesired elements discarded. To explicitly remove an entire tuple,

just use the del statement.

Example:
tup = ('physics', 'chemistry', 1997, 2000);
print(tup);
del(tup);
SET

A set is a collection which is unordered and unindexed.

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.

How to Define
A set is created by placing all the items (elements) inside curly braces {}, separated by
comma or by using the built-in function set().

For Example:
S = {10,20,30,40}
S={'Programming', 'Networking', 'Database'}
S={('Programming', 'Python'), ('Networking', 'Database')}

It can have any number of items and they may be of different types (integer, float, tuple,
string etc.).

But a set cannot have a mutable element, like list, set or dictionary, as its element.

S={['Programming', 'Python'], ['Networking', 'Database']}


Above one not permitted in python.

Access Items
We cannot access items in a set by referring to an index, since sets are unordered the items
has no index.

But we can loop through the set items using a for loop, or ask if a specified value is present
in a set, by using the in keyword.

S={'Programming', 'Networking', 'Database'}


for x in S:
print(x)

Methods of Set class


For adding items in a set
To add one item to a set use the add() method.

To add more than one item to a set use the update() method.

add(item)

Add an item to a set, using the add() method:

S={'Programming', 'Networking', 'Database'}


S.add('Data Science')

print(S)
update(list of items)

Add multiple items to a set, using the update() method:

S={'Programming', 'Networking',
'Database', 'Data Science'}

S.update(['Java','CCNA','Oracle'])

print(S)

For removing/deleting items from a set

To remove an item in a set, use the remove(), or the discard() method.

remove(item)

Remove a item passed as argument from a set.

S={'Programming', 'Networking',
'Database', 'Data Science', 'Java','CCNA','Oracle'}
S.remove('Data Science')

print(S)

If the item to remove does not exist, remove() will raise an error.

discard(item)

Remove a item passed as argument from a set.

S={'Programming', 'Networking',
'Database', 'Java','CCNA','Oracle'}
S.discard('Java')

print(S)

If the item to remove does not exist, discard() will not raise an error.

pop()

Remove the last item by using the pop() method:

The return value of the pop() method is the removed item.

S={'Programming', 'Networking',
'Database','CCNA','Oracle'}
e=S.pop()
print(e) # e will contain item which is removed

clear()

Remove all elements from the S set:

S={'Programming', 'Networking', 'Database','CCNA'}


S.clear()

print(S)

Operations on Set

union()

The union() method returns a new set with all items from both sets.

set1 = {"a", "b" , "c",2}


set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)

we can replace union method with operator ‘ | ’ as


set3 = set1 | set2

intersection()

Return a set that contains the items that exist in both set x, and set y.

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

z = x.intersection(y)
print(z)

we can replace intersection method with operator ‘ & ’ as


z=x&y

difference()

Return a set that contains the items that only exist in set calling set object (x),
and not in set passed as argument (y).

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
z = x.difference(y) # z = x – y not equal y –x
print(z)

x.difference_update(y) #x=x–y
print(z)

we can replace difference method with operator ‘ - ’ as


z=x-y

Other Methods for Set class

Method Description

copy() Returns a copy of the set

difference_update() Removes the items in this set that are also included in another, specified
set

intersection_update() Removes the items in this set that are not present in other, specified
set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and another

Dictionary
Dictionaries are used to store data values in key:value pairs. Keys in dictionaries are unique.

How to Define
Dictionaries are written with curly brackets, and have keys and values:

For Example:

D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}
print(D1)

A dictionary is a collection which is ordered, changeable and does not allow duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.

Dictionary Items
The values in dictionary items can be of any data type

e.g. String, int, boolean, and list data types:

D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020,
"Subject": ['MGT','MAD','WBP','PWP'],
"result":{'FY':67,'SY':78,'TY':89}
}

Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:

Get the value of the "Dept" key:

D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}
print(D1[‘Dept’])

Output
Computer

Update Dictionaries
You can change the value of a specific item by referring to its key name:
Change the "year" to 2018:

D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}

D1["Year"] = 2021

print(D1[‘Year’])

Output
2021

Methods in Dictionary

To Access Dictionary Items

get()

The get() method returns the value of the item with the specified key.

dict_class_object.get(key, value)

Key: Required. The key of the element or item you want to get the
value from

Value: Optional. A value to return if the key does not exist.

D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}

s = D1.get("Name", "Student")

print(s)

Output
Aman

keys()
The keys() method will return a list of all the keys in the dictionary.

D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}

s = D1.keys()

print(s)

Output
dict_keys(['Name', 'Dept', 'Year'])

In above one ‘s’ is automatically updated if any changes done to


the dictionary means it will be reflected in the keys list ‘s’.

values ()

The values () method will return a list of all the values in the dictionary.

D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}

v = D1.values()

print(v)

Output
dict_values(['Aman', 'Computer', 2020])

In above one ‘v’ is automatically updated if any changes done to


the dictionary means it will be reflected in the values list ‘v’.

items()

The items() method will return each item in a dictionary, as tuples in a list.
D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}

i = D1.items()

print(i)

Output
dict_items([('Name', 'Aman'), ('Dept', 'Computer'), ('Year', 2020)])

In above one ‘i’ is automatically updated if any changes done to


the dictionary means it will be reflected in the items list ‘i’.

update()

The update() method will update the dictionary with the items from the given argument.

D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}

D1.update({'subject':['MGT','MAD','WBP','PWP']})

print(D1)

Output
{'Name': 'Aman', 'Dept': 'Computer', 'Year': 2020, 'subject': ['MGT', 'MAD', 'WBP', 'PWP']}

pop()
The pop() method removes the item with the specified key name:

D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020,
"subject":['MGT','MAD','WBP','PWP']
}

i = D1.pop('subject')

print('Removed Item value is',i)

Output
Removed Item value is ['MGT', 'MAD', 'WBP', 'PWP']

popitem()

The popitem() method removes the last inserted item or a random item is removed instead.
(before version 3.7).

The pop() method removes the item with the specified key name:

D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020,
}

i = D1.popitem()

print('Removed Item is',i)

Output
Removed Item is ('Year', 2020)
Loop Through a Dictionary

You can loop through a dictionary by using a for loop.


When looping through a dictionary, the return value are the keys of the dictionary, but
there are methods to return the values as well.

D1= {
"Name": "Aman",
"Dept": "Computer",
"Year": 2020
}

for x in D1:
print(x)

Output
Name
Dept
Year

LIST OF DICTIONARY METHODS

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the
specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

You might also like