0% found this document useful (0 votes)
1 views19 pages

Python Unit 3

This document provides an overview of data structures in Python, focusing on iterators, lists, tuples, and dictionaries. It explains how to create, manipulate, and access these data structures, highlighting their key characteristics and built-in methods. The document includes code examples to illustrate the concepts discussed.

Uploaded by

Owais Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
1 views19 pages

Python Unit 3

This document provides an overview of data structures in Python, focusing on iterators, lists, tuples, and dictionaries. It explains how to create, manipulate, and access these data structures, highlighting their key characteristics and built-in methods. The document includes code examples to illustrate the concepts discussed.

Uploaded by

Owais Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 19

Python Programming Unit-3 Notes

CHAPTER 3- Data Structures in Python

Iterators
An iterator is an object that contains a countable number of values. It is an object that can be
iterated upon, meaning that you can traverse through all the values.

# Python program to illustrate iterating over a list

print("List Iteration")
l = ["ABC", "BCD", "CDE"]
for i in l:
print(i)

List Iteration
ABC
BCD
CDE

# Iterating over a tuple (immutable)

print("Tuple Iteration")
t = ("ABC", "BCD", "CDE")
for i in t:
print(i)

Tuple Iteration
ABC
BCD
CDE

# Iterating over a String

print("String Iteration")
s = "ABCDE"
for i in s :
print(i)

String Iteration
A
B
C
D
E

1
Python Programming Unit-3 Notes

Python has four basic inbuilt data structures namely Lists, Tuple, Dictionary and Set.
List
Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be
any type. The values in list are called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the elements in square brackets
(“[” and “]”)

# Creating a List

List = [ ]
print("Blank List: ", List)

Blank List:
[]

# Creating a List of numbers

List = [10, 20, 30]


print("List of numbers: ")
print(List)

List of numbers:
[10, 20, 30]

# Creating a List of strings and accessing using index

List = ["Programming", "in", "Python"]


print("List Items: ")
print(List[0])
print(List[2])

List Items:
Programming
Python

# Creating a Multi-Dimensional List (By Nesting a list inside a List)

List = [['Programming', 'in'] , ['Python']]


print("Multi-Dimensional List: ")
print(List)

Multi-Dimensional List:
[['Programming', 'in'], ['Python']]

2
Python Programming Unit-3 Notes

A list may contain duplicate values with their distinct positions and hence, multiple distinct or duplicate
values can be passed as a sequence at the time of list creation.

#Creating a List with the use of Numbers/(Having duplicate values)


vvvvvvvalues)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("List with the use of Numbers: ")
print(List)

List with the use of Numbers:


[1, 2, 4, 4, 3, 3, 3, 6, 5]

# Creating a List with mixed type of values (Having numbers and strings)

List = [1, 2, 'Programming', 4, 'in', 6, 'Python']


print("List with the use of Mixed Values: ")
print(List)

List with the use of Mixed Values:


[1, 2, 'Programming', 4, 'in', 6, Python']

Unlike strings, lists are mutable because you can change the order of items in a list or reassign an
item in a list. When the bracket operator appears on the left side of an assignment, it identifies
the element of the list that will be assigned.

Updating a List elements (List are mutable)


Numbers=[17,123]
Print(“Before:”, Numbers)
Numbers[1]=5
Print (“After:”, Numbers)

Before: [17, 123]


After: [17,5]

Using len() function we can find the length (no. of elements in list) of list.

# Creating a List of numbers and finding the length

List = [10, 20, 14]


print(len(List))

3
Python Programming Unit-3 Notes

List operation

# The + operator concatenates lists

a = [1, 2, 3]
b = [4, 5, 6]
c=a+b
print(c)

[1, 2, 3, 4, 5, 6]

# The * operator repeats a list a given number of times

a = [1]
a=a*3
print(a)

[1, 1, 1]

List slices

# The slice operator

List = ['a', 'b', 'c', 'd', 'e', 'f']


print(List[1:3])
print(List[:4])
print(List[3:])

['b', 'c']
['a', 'b', 'c', 'd']
['d', 'e', 'f']

If you omit the first index, the slice starts at the beginning. If you omit the second, the slice
goes to the end. So, if you omit both, the slice is a copy of the whole list.

List = ['a', 'b', 'c', 'd', 'e', 'f']


print(List[:])

['a', 'b', 'c', 'd', 'e', 'f']

4
Python Programming Unit-3 Notes

A slice operator on the left side of an assignment can update multiple elements.

List = ['a', 'b', 'c', 'd', 'e', 'f']


List[1:3] = ['x', 'y']
print(List)

['a', 'x', 'y', 'd', 'e', 'f']

List methods
Python has a set of built-in methods that you can use on lists.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

# append()

fruits = ['apple', 'banana', 'cherry']


fruits.append("orange")
print(fruits)

['apple', 'banana', 'cherry', 'orange']

5
Python Programming Unit-3 Notes

# clear()

fruits = ['apple', 'banana', 'cherry', 'orange']


fruits.clear()
print(fruits)

[]

# copy()

fruits = ['apple', 'banana', 'cherry', 'orange']


x = fruits.copy()
print(x)

['apple', 'banana', 'cherry', 'orange']

# count()

fruits = ['apple', 'banana', 'cherry']


x = fruits.count("cherry")
print(x)

#extend()
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)

['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']

#index()

fruits = ['apple', 'banana', 'cherry']


x = fruits.index("cherry")
print(x)

6
Python Programming Unit-3 Notes

#insert()

fruits = ['apple', 'banana', 'cherry']


fruits.insert(1, "orange")
print(fruits)

['apple', 'orange', 'banana', 'cherry']

#pop()

fruits = ['apple', 'banana', 'cherry']


fruits.pop(1)
print(fruits)

['apple', 'cherry']

#remove()

fruits = ['apple', 'banana', 'cherry']


fruits.remove("banana")
print(fruits)

['apple', 'cherry']

#reverse()

fruits = ['apple', 'banana', 'cherry']


fruits.reverse()
print(fruits)

['cherry', 'banana', 'apple']

#sort()

cars = ['Ford', 'BMW', 'Volvo']


cars.sort()
print(cars)

['BMW', 'Ford', 'Volvo']

7
Python Programming Unit-3 Notes

Tuples
A tuple is a sequence of immutable (A tuple is a collection which is ordered and unchangeable) 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 is as simple as putting different comma-separated values. Optionally you can put these
comma-separated values between parentheses also. For example

# creating a tuple

tup1 = ('ABC', 'pqr', 1000, 2000);


tup2 = (1, 2, 3, 4, 5);
tup3 = "a", "b", "c", "d";
print(tup1)
print(tup2)
print(tup3)

('ABC', 'pqr', 1000, 2000)


(1, 2, 3, 4, 5)
('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,);

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
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. For example

# accessing a tuple

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5, 6, 7);
print("tup1[0]: ", tup1[0])
print("tup2[1:5]: ", tup2[1:5])

tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)

8
Python Programming Unit-3 Notes

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 as the following example
demonstrates

# updating a tuple

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)

(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. For example

# deleting a tuple

tup = ('ABC', 'pqr', 1997, 2000);


print(tup)
del tup;
print("After deleting tup : ")
print(tup)

This produces the following result. Note an exception raised, this is because after del tup tuple does
not exist any more

('ABC', 'pqr', 1997, 2000)


After deleting tup :

NameError Traceback (most recent call last)


<ipython-input-54-692273a13f26> in <module>
3deltup;
4print("After deleting tup : ")
----> 5print(tup)
NameError: name 'tup' is not defined

9
Python Programming Unit-3 Notes

Tuple Operations
Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here
too, except that the result is a new tuple, not a string

Python Expression Results Description

T=(1,2,3)
3 Length
print(len(T))

T=(1, 2, 3)+(4, 5, 6)
(1, 2, 3, 4, 5, 6) Concatenation
print(T)
T=('Hi!',)* 4
('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
Print(T)
T=(1,2,3)
True Membership
Print(3 in (T))
for x in (1, 2, 3): 1
print(x) 2 Iteration
3

Indexing, Slicing, Matrices


Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings.
Assuming following input

L = ('spam', 'Spam', 'SPAM!')

Python Expression Results Description

print(L[2]) 'SPAM!' Offsets start at zero

print(L[-2]) 'Spam' Negative: count from the right

print(L[1:]) ['Spam', 'SPAM!'] Slicing fetches sections

len() function
len() is one of the built-in functions in python. It returns the number of items in an object.
When the object is a string, the len() function returns the number of characters in the string.

10
Python Programming Unit-3 Notes

# len()

tuple1, tuple2 = (123, 'xyz', 'zara'), ('abc')


print("First tuple length : ", len(tuple1))
print("Second tuple length : ", len(tuple2))

First tuple length : 3


Second tuple length : 3

Dictionary
A dictionary is mutable and is another container type that can store any number of Python objects,
including other container types. Dictionaries consist of pairs (called items) of keys and their
corresponding values.
Python dictionaries are also known as associative arrays or hash tables. The general syntax of a
dictionary is as follows

d1 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

You can create dictionary in the following way as well:

d1 = { 'abc': 456 };
d2 = { 'abc': 123, 98.6: 37 };

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole
thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly
braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any
type, but the keys must be of an immutable data type such as string s, numbers, or tuples.
Accessing Values in Dictionary
To access values in tuple, use the square brackets for slicing along with the index or indices to obtain
value available at that index. For example

# accessing a dictionary

d1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};


print("Name:", d1['Name']);
print("Age:", d1['Age']);
print("Class:", d1['Class']);

Name: Zara
Age: 7
Class: First

11
Python Programming Unit-3 Notes
If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as
follows

d1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};


print("d1['Alice']: ", d1['Alice'])

KeyError Traceback (most recent call last)


<ipython-input-58-d6f7f5c44745> in <module>
1 d1 ={'Name':'Zara','Age':7,'Class':'First'};
----> 2print("d1['Alice']: ", d1['Alice'])
KeyError: 'Alice'

Updating Dictionary
You can update a dictionary by adding a new entry or item(i.e., a key-value pair), modifying an existing
entry, or deleting an existing entry as shown below in the simple example

# updating dictionary
d1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print
(d1)
d1['Age'] = 8; # update existing entry
d1['School'] = "LJP"; # Add new entry
print ("d1['Age']: ", d1['Age'])
print ("d1['School']: ", d1['School'])
print (d1)

{'Name': 'Zara', 'Age': 7, 'Class': 'First'}


d1['Age']: 8
d1['School']: LJP
{'Name': 'Zara', 'Age': 8, 'Class': 'First', 'School': 'LJP'}

Deleting Dictionary Elements


To explicitly remove an entire dictionary, just use the del statement.

# deleting dictionary
d1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print("Name:",d1['Name'])
del d1['Name']; # remove entry with key 'Name'
print(d1)
d1.clear(); # remove all entries in d1
print(d1)
del d1 ; # delete entire dictionary
print(d1)

12
Python Programming Unit-3 Notes

{'Name': 'Zara', 'Age': 7, 'Class': 'First'}


d1['Age']: 8
d1['School']: LJP
{'Name': 'Zara', 'Age': 8, 'Class': 'First', 'School': 'LJP'}

Build-in Dictionary Functions & Methods


Method Description
d1.clear() Removes all elements of dictionary d1
d1.copy() Returns a shallow copy of dictionary d1
d1.get(key, default=None) Returns the value of the item with the specified key
d1.items() Returns a list of d1's (key, value) tuple pairs
d1.keys() Returns list of dictionary d1's keys
d1.update(d2) Adds dictionary d2's key-values pairs to d1
d1.values() Returns list of dictionary d1's values

# clear()

d1 = {'Name': 'Zara', 'Age': 7};


print("Start Len:", len(d1))
d1.clear()
print("End Len:", len(d1))

Start Len: 2
End Len: 0

# copy()

d1 = {'Name': 'Zara', 'Age': 7};


d2 = d1.copy()
print("New Dictionary:", str(d2))

New Dictionary: {'Name': 'Zara', 'Age': 7}

# get()

d1 = {'Name': 'Zara', 'Age': 7}


print("Value:", d1.get('Age'))
print("Value:", d1.get('Education', "Never"))
print(d1.get('c'))

Value: 7
Value: Never
None

13
Python Programming Unit-3 Notes

# items()

d1 = {'Name': 'Zara', 'Age': 7}


print("Value:", d1.items())

Value : dict_items([('Name', 'Zara'), ('Age', 7)])

# keys()

d1 = {'Name': 'Zara', 'Age': 7}


print("Keys:", d1.keys())

Keys: dict_keys(['Name', 'Age'])

#values()

d1 = {'Name': 'Zara', 'Age': 7}


print("Values:", d1.values())

Values: dict_values(['Zara', 7])

# update()

d1 = {'Name': 'Zara', 'Age': 7}


d2 = {'Gender': 'female'}
d1.update(d2)
print("Value:", d1)

Value: {'Name': 'Zara', 'Age': 7, 'Gender': 'female'}

14
Python Programming Unit-3 Notes

Set
Sets are used to store multiple items in a single variable. A set is a collection which is
unordered and unindexed. Sets are written with curly brackets.

# creating set

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


print(thisset)

{'banana', 'apple', 'cherry'}

Note: Sets are unordered, so you cannot be sure in which order the items will appear.

Duplicates Not Allowed


Sets cannot have two items with the same value.

# creating set

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


print(thisset)

{'banana', 'apple', 'cherry'}

Set Items - Data Types


Set items can be of any data type.

# string, int and boolean data types

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


set2 = {1, 5, 7, 9, 3} #in numeric, it will print in order.
set3 = {True, False, False}
set4= {"abc", 34, True, 40, "male"} # set with strings, integers and boolean values
print(set1)
print(set2)
print(set3)
print(set4)

{'banana', 'cherry', 'apple'}


{1, 3, 5, 7, 9}
{False, True}
{True, 34, 'male', 40, 'abc'}

15
Python Programming Unit-3 Notes

Access Items
You cannot access items in a set by referring to an index or a key. But you can loop through the set
itemsusing a for loop, or ask if a specified value is present in a set, by using the in keyword.

# loop through the set, and print the values

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


for x in thisset:
print(x, end=",")

cherry,banana,apple,

# check if "apple" is present in the set:

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


print("apple" in thisset)

True

Add Items
Once a set is created, you cannot change its items, but you can add new items. To add one item to a
set usethe add() method.

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


thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)

{'cherry', 'orange', 'banana', 'apple'}

To add items from another set into the current set, use the update() method.

# add elements from tropical into thisset

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


tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)

16
Python Programming Unit-3 Notes

{'banana', 'mango', 'apple', 'cherry', 'papaya', 'pineapple'}

Add Any Iterable


The object in the update() method does not have to be a set, it can be any iterable object (tuples,
lists, dictionaries etc.).

# add elements from tropical into thisset

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


mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)

{'cherry', 'kiwi', 'orange', 'banana', 'apple'}

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

# remove "apple" by using the remove() method

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


thisset.remove("apple")
print(thisset)

{'cherry', 'banana'}

# remove "apple" by using the discard() method

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


thisset.discard("apple")
print(thisset)

{'cherry', 'banana'}

17
Python Programming Unit-3 Notes

You can also use the pop() method to remove an item, but this method will remove the last item.
Rememberthat sets are unordered, so you will not know what item that gets removed. The return value
of the pop() method is the removed item.

# remove the last item by using the pop() method

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


x = thisset.pop()
print(x)
print(thisset)

cherry
{'banana', 'apple'}

#clear() method empties the set

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


thisset.clear()
print(thisset)

set()

#del keyword will delete the set completely

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


del thisset
print(thisset)

NameError Traceback (most recent call last)


<ipython-input-24-2ec9feb8cb8a> in <module>
1 thisset = {"apple", "banana", "cherry"}
2 del thisset
----> 3 print(thisset)
NameError: name 'thisset' is not defined

18
Python Programming Unit-3 Notes

Join Sets
There are several ways to join two or more sets in Python. You can use the union() method that returns
a new set containing all items from both sets, or the update() method that inserts all the items from
one set into another.

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

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


set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

{1, 'c', 2, 3, 'a', 'b'}

#update() method inserts the items in set2 into set1

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


set2 = {1, 2, 3}
set1.update(set2)
print(set1)

{1, 'c', 2, 3, 'a', 'b'}

Note: Both union() and update() will exclude any duplicate items.

19

You might also like