0% found this document useful (0 votes)
75 views50 pages

Unit 2

Uploaded by

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

Unit 2

Uploaded by

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

Department of Computer Science and Engineering (CSE)

INSTITUTE : UIE
DEPARTMENT : CSE
Bachelor of Engineering (Computer
Science & Engineering)
Programming in Python Lab
(23CSP-201)

DISCOVER . LEARN .
EMPOWER
Department of Computer Science and Engineering (CSE)
Unit 2 Content

UNIT-2 Operations on Strings, list, Tuples, Sets &


Dictionaries

Experiment 2.1 String operations and methods (indexing, slicing, len(), strip(), find(), replace(), split(), join(), etc.).

Experiment 2.2 List creation, accessing, and operations (append (), insert(), extend(), remove(), pop(), sort(), etc.).

Experiment 2.3 Tuple creation, accessing, and operations: Demonstrate various methods of creating tuples,
accessing tuple elements through indexing and slicing, and applying tuple methods/functions.

Experiment 2.4 Sets and Dictionaries creation, accessing, and operations.

2
Department of Computer Science and Engineering (CSE)

Course Outcome

CO1 Describe the basic fundamentals of python


programming.
Will be covered in
CO2 Apply the python programming for Arithmetic,
Logical and sorting operations. this lecture
CO3 Analyze python programming loops & methods
for data manipulation.

CO4 Use the Python programming language for


various programming techniques like list,
tuples, dictionaries etc.

CO5 Develop application software using object-


oriented programming techniques in the
Python language.

3
Department of Computer Science and Engineering (CSE)

OBJECTIVES
At the completion of this Chapter, students should be able to do the following:
1. Proficiently manipulate strings, lists, tuples, sets, and dictionaries in
Python, demonstrating a clear understanding of their unique properties
and methods.
2. Apply appropriate data structures (strings, lists, tuples, sets, or
dictionaries) to solve various programming problems, showcasing the
ability to choose the most suitable structure for different scenarios.
3. Implement and debug code using these data structures, utilizing their
respective methods and operations effectively to create efficient and
readable Python programs.

University Institute of Engineering (UIE)


Python Data Structures

• In Python, data structures are used to organize and store data efficiently. Python
provides a variety of built-in data structures, each with its own characteristics and use
cases.

University Institute of Engineering (UIE)


Python Data Structures

• List: List is an ordered collection of elements enclosed within [].


• A list can store a collection of data of any size.
• A list is a sequence defined by the list class.
• It contains the methods for creating, manipulating, and processing lists.
• There are addresses assigned to every element of the list, which is called as
Index.
• Elements in a list can be accessed through an index.
• Lists are mutable.
• The elements in a list are separated by commas.
• A list can contain the elements of the same type or mixed types.

University Institute of Engineering (UIE)


Python Data Structures

• List Is a Sequence Type: A sequence type in Python is a collection of objects


ordered by position, where each element can be accessed using an index.
Strings and lists are sequence types in Python. A string is a sequence of
characters, while a list is a sequence of any elements.

Common Operations for


Sequences

University Institute of Engineering (UIE)


Python Data Structures

• Functions for Lists: Several Python built-in functions can be used with lists.

University Institute of Engineering (UIE)


Python Data Structures

• Index Operator []: An element in a list can be accessed through the


index operator, using the following syntax:
• myList[index]
• List indexes are 0 based; that is, they range from 0 to len(myList)-1.

The list myList


has 10 elements
with indexes
from 0 to 9.

University Institute of Engineering (UIE)


Python Data Structures

• Python also allows the use of negative numbers as indexes to reference


positions relative to the end of the list.
• The actual position is obtained by adding the length of the list with the
negative index. For example:

University Institute of Engineering (UIE)


Python Data Structures

• List Slicing [start : end]: The index operator allows you to select an element at
the specified index. The slicing operator returns a slice of the list using the
syntax list[start : end]. The slice is a sublist from index start to index end – 1.
Here are some examples.

University Institute of Engineering (UIE)


Python Data Structures

• List Slicing [start : end]

University Institute of Engineering (UIE)


Python Data Structures

• The +, *, and in/not in Operators:

University Institute of Engineering (UIE)


Python Data Structures

• Traversing Elements in a for Loop: The elements in a Python list are iterable.
Python supports a convenient for loop, which enables you to traverse the list
sequentially without using an index variable. For example, the following code
displays all the elements in the list myList:

• for u in myList:
• print(u)

University Institute of Engineering (UIE)


Python Data Structures

• List Methods: append, count, extend, index, and insert methods

University Institute of Engineering (UIE)


Python Data Structures

• List Methods: insert, pop, remove, reverse, and sort methods

University Institute of Engineering (UIE)


Python Data Structures

• Inputting Lists

University Institute of Engineering (UIE)


Python Data Structures

• Copying Lists: To copy the data in one list to another list, you have to copy
individual elements from the source list to the target list.
• You often need to duplicate a list or part of a list in a program. In such cases
you could attempt to use the assignment statement (=), as follows:
• list2 = list1

University Institute of Engineering (UIE)


Python Data Structures

• list2 = list1

University Institute of Engineering (UIE)


Python Data Structures

• Strings: Strings in python are surrounded by either single quotation marks, or


double quotation marks.
• 'hello' is the same as "hello".
• Strings are immutable, meaning they cannot be changed once created.
• Characters of a String can be accessed by using the method of Indexing.
• Indexing allows negative address references to access characters from the back
of the String.
• We can create a string using the constructor of the str class as:
s1=str() #creates an empty string
s2=str(“hello”) #creates a string object for hello

University Institute of Engineering (UIE)


Python Data Structures

• Python string methods is a collection of in-built Python functions that operates


on lists.
• These methods allow you to manipulate and perform various operations on
strings, such as finding substrings, replacing characters, converting cases, and
more.
• Upper: string.upper() converts a string to uppercase.
• Lower: string.lower() converts a string to lowercase.
• Concatenation: str1 + str2 combines two strings.
• Length: len(string) returns the length of a string.
• Find: string.find(substring) locates the index of the first occurrence of a
substring.

University Institute of Engineering (UIE)


Python Data Structures

• Count: string.count(substring) counts the occurrences of a substring in a string.


• Replace: string.replace(old, new) replaces occurrences of a substring with
another substring.
• Strip: string.strip() removes leading and trailing whitespace.
• StartsWith: string.startswith(prefix) checks if a string starts with a specified
prefix.
• EndsWith: string.endswith(suffix) checks if a string ends with a specified suffix.
• Split: string.split(separator) splits a string into a list of substrings based on a
separator.
• Join: separator.join(list) joins a list of strings into a single string with a
separator.

University Institute of Engineering (UIE)


Python Data Structures

• How To Index and Slice Strings in Python?


• Indexing: Indexing means referring to an element of an iterable by its position
within the iterable. Each of a string’s characters corresponds to an index
number and each character can be accessed using its index number.

University Institute of Engineering (UIE)


Python Data Structures

• Slicing: Slicing in Python is a feature that enables accessing parts of the


sequence. In slicing a string, we create a substring, which is essentially a string
that exists within another string.

University Institute of Engineering (UIE)


Python Data Structures

• Testing strings:
• String class in python has various inbuilt methods which allows to check for
different types of strings.
• s = "welcome to python"
• print(s.isalnum())
• print("Welcome".isalpha())
• print("2012".isdigit())
• print("first Number".isidentifier())
• print(s.islower())
• print("WELCOME".isupper())
• print(" \t".isspace())

University Institute of Engineering (UIE)


Python Data Structures

• Formatting String :
• s = “ string in python”
• s1 = s.center(20) # place the string in the center with 20 char
• print(s1)
• s = “ string in python”
• s1 = s.ljust(20) # place the string in the left with 20 char
• print(s1)
• s = “ string in python”
• s1 = s.rjust(20) # place the string in the right with 20 char
• print(s1)

University Institute of Engineering (UIE)


Python Data Structures

• Tuples : Tuples are like lists, but their elements are fixed; that is, once a tuple is
created, cannot add new elements, delete elements, replace elements, or
reorder the elements in the tuple. Tuple is immutable.
• A tuple is very much like a list, except that its elements are fixed.
• It is enclosed within ().

University Institute of Engineering (UIE)


Python Data Structures

University Institute of Engineering (UIE)


Python Data Structures

• Cannot modify a tuple because it is immutable.

University Institute of Engineering (UIE)


Python Data Structures

• Cannot modify a tuple because it is immutable.

University Institute of Engineering (UIE)


Python Data Structures

• Sets : Sets are like lists storing a collection of elements.


• Unlike lists, however, the elements in a set are nonduplicates and are not placed
in any particular order.
• It is enclosed within { }.
• A set can contain the elements of the same type or mixed types.
• For example, s ={1, 2, 3, "one", "two", "three"} is a set that contains numbers
and strings.
• Set items are unchangeable, but you can remove items and add new items.
• Sets cannot have two items with the same value.

University Institute of Engineering (UIE)


Python Data Structures

• Manipulating and Accessing Sets: Add an element to a set or remove an


element by using the add(e) or remove(e) method. You can use the len, min,
max, and sum functions on a set, and a for loop to traverse all elements in a set.
• Use in or not in operator to determine whether an element is in the set.

University Institute of Engineering (UIE)


Python Data Structures

• Manipulating and Accessing Sets

The remove(e) method will throw a KeyError


exception if the element to be removed is not
in the set.

University Institute of Engineering (UIE)


Python Data Structures

• Manipulating and Accessing Sets

University Institute of Engineering (UIE)


Python Data Structures

• Equality Test: the == and != operators to test if two sets contain the same
elements. For example:

University Institute of Engineering (UIE)


Python Data Structures

• Set Operations: Python provides the methods for performing set union,
intersection, difference, and symmetric difference operations.
• The union of two sets is a set that contains all the elements from both sets.
• Use the union method or the | operator to perform this operation. For example:

University Institute of Engineering (UIE)


Python Data Structures

• Set Operations: Python provides the methods for performing set union,
intersection, difference, and symmetric difference operations.
• The intersection of two sets is a set that contains the elements that appear in
both sets. Use the intersection method or the & operator to perform this
operation. For example:

University Institute of Engineering (UIE)


Python Data Structures

• Set Operations: Python provides the methods for performing set union,
intersection, difference, and symmetric difference operations.
• The difference between set1 and set2 is a set that contains the elements in set1
but not in set2. Use the difference method or the - operator to perform this
operation.
• For example:

University Institute of Engineering (UIE)


Python Data Structures

• Set Operations: Python provides the methods for performing set union,
intersection, difference, and symmetric difference operations.
• The symmetric difference (or exclusive or) of two sets is a set that contains the
elements in either set, but not in both sets. You can use the
symmetric_difference method or the ^ operator to perform this operation. For
example:

University Institute of Engineering (UIE)


Python Data Structures

University Institute of Engineering (UIE)


Python Data Structures

• Dictionaries: A dictionary is a container object that stores a collection of


key/value pairs.
• It enables fast retrieval, deletion, and updating of the value by using the key.
• A dictionary is an efficient data structure for such a task.
• A dictionary is a collection that stores the values along with the keys. The keys
are like an index operator.
• A dictionary cannot contain duplicate keys. Each key maps to one value.
• A key and its corresponding value form an item (or entry) stored in a dictionary.

University Institute of Engineering (UIE)


Python Data Structures

• Dictionaries: The data structure is a called a “dictionary” because it resembles a


word dictionary, where the words are the keys and the words’ definitions are
the values.
• A dictionary is also known as a map, which maps each key to a value.
• Dictionary is mutable.
• Creating a Dictionary: Create a dictionary by enclosing the items inside a pair of
curly braces ({}). Each item consists of a key, followed by a colon, followed by a
value. The items are separated by commas.

University Institute of Engineering (UIE)


Python Data Structures

University Institute of Engineering (UIE)


Python Data Structures

• Adding a new element, changing an existing element, update, pop

University Institute of Engineering (UIE)


Python Data Structures

• Adding a new element, changing an existing element, update, pop, clear

University Institute of Engineering (UIE)


Python Data Structures

• Difference between list, tuple, set and dictionary


List Tuple Set Dictionary

List is a non-homogeneous data Tuple is also a non-homogeneous Set data structure is also non- Dictionary is also a non-
structure that stores the elements in data structure that stores single row homogeneous data structure but homogeneous data structure which
single row and multiple rows and and multiple rows and columns stores in single row stores key value pairs
columns

List can be represented by [ ] Tuple can be represented by ( ) Set can be represented by { } Dictionary can be represented by {
}

List allows duplicate elements Tuple allows duplicate elements Set will not allow duplicate Set will not allow duplicate
elements elements and dictionary doesn’t
allow duplicate keys.

University Institute of Engineering (UIE)


Python Data Structures

• Difference between list, tuple, set and dictionary


List Tuple Set Dictionary

List can be created using list() Tuple can be created using tuple() Set can be created using set() Dictionary can be created using
function function. function dict() function.

List is mutable i.e we can make any Tuple is immutable i.e we can not Set is mutable i.e we can make Dictionary is mutable. But Keys
changes in list. make any changes in tuple any changes in set. But are not duplicated.
elements are not duplicated.

Creating an empty list Creating an empty Tuple Creating a set Creating an empty dictionary
d={}
l=[] t=() a=set()

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Outcomes

• Apply Python's built-in data structures (strings, lists, tuples,


sets, and dictionaries) to manipulate and organize data
effectively.

• Implement appropriate methods and operations for each data


structure to solve practical programming problems.

• Analyze and select the most suitable data structure for


different programming scenarios, demonstrating
understanding of their unique characteristics and
performance implications.

University Institute of Engineering (UIE)


Python Data Structures

• SUGGESTED TEXTBOOKS
• Ashok Namdev Kamthane, Programming and Problem Solving with Python, Mc Graw Hill Education
Publication, 1st Edition, November 2017.
• Kenneth Lambert, Fundamentals of Python :First Programs, Cengage Learning
• Allen Downey, Think Python, O'Reilly Media, 2nd Edition,2015.

• REFERENCE BOOKS
• Rajaraman V,” Computer Oriented Numerical Methods”, Pearson Education.
• Y. Daniel Liang, Introduction to Programming Using Python, Pearson.
• Martin C.Brown, PYTHON The Complete REFERENCE, Tata McGraw-Hill
Education, 4th Edition, March 2018.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

University Institute of Engineering (UIE)

You might also like