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

Unit III Data Structures

The document provides an overview of data structures in Python, focusing on Lists, Tuples, and Sets. It covers their definitions, creation, accessing methods, built-in functions, and methods specific to each data structure. Key operations such as adding, deleting, and manipulating elements are also discussed, along with examples for clarity.

Uploaded by

sakharkarsadia
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unit III Data Structures

The document provides an overview of data structures in Python, focusing on Lists, Tuples, and Sets. It covers their definitions, creation, accessing methods, built-in functions, and methods specific to each data structure. Key operations such as adding, deleting, and manipulating elements are also discussed, along with examples for clarity.

Uploaded by

sakharkarsadia
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Programming in Python

(23DCE2101)

(As per NEP 2023 pattern)

Prof. S.M. Sabale


Head of Computer Engineering (Diploma)
Dr. Babasaheb Ambedkar Technological University, Lonere
Unit III

Data Structures in Python

• Learn concepts of Lists, Tuples, Sets, Dictionaries


• Defining, Accessing, Deleting, Updating
• Operations and built-in functions
Lists
• Ordered collection of items/Sequence of items
• Elements may be homogeneous/heterogeneous
• Linear data structure
• Define
<list_name> = [value1, value2, …., <valuen]
Examples: list1 = [10, 20, 30, 40]
list2 = [34, “76”, 18.76, “ABC”]
• Creating a List:
>> l1 = [] # empty list
>> l1 = list() # empty list using a constructor
>> l2 = [10, 20, 30,40,50]
>> l2 = list([10, 20, 30,40,50])
>> l3 = [1, 2.0, “abs”]
>> l4 = list(range(0,5) # [0,1,2,3,4]
>> l5=list(“ABC”) # [‘A’,’B’,’C’]
• Accessing values in list:
>> l2[0]
10
>> l2[-2]
40
>> l2[1:3]
[20, 30]
>> l2[3:]
[40, 50]
>> l2[:4]
[10, 20, 30, 40]
• Deleting values in a List:
1) pop() method in a Python is used to remove a particular item/element from the
given index in the list. The pop() method removes and returns the last item if index
is not provided. This helps us implement the list as stack (First In, Last Out data
structure).
• Ex. For pop() method,
>> list=[10,20,30,40]
>>> list.pop(2) # pop with index
30
>>> list
[10, 20, 40]
>>> list.pop() # pop without index
40
>>> list
[10, 30]
2) We can delete one or more items from a list using the keyword ‘del ‘. It can
even delete the list entirely. But it does not store the value for further use.
>>> list=[10, 20, 30, 40]
>>> del (list[1]) # del with index
>>> list
[10, 30, 40]
>>> del list # del without index
>>> list
<class ‘list’>
3) The remove() method in a Python is used to remove a particular element from the
list. We use the remove() method if we know the item that we want to remove or
delete from the list (but not the index).
EX.
>>> list=[10, ’one’, 20, ’two’] # heterogeneous list
>>> list.remove(20) # remove element 20
>>> list
[10, ’one’, ’two’]
>>> list.remove(‘one’)
>>> list
[10, ’two’]
Built in Functions for List
Sr. No. Built-in function Description Example
list1=[1 , 2, 3, 4, 8]
1 len(list) It returns the length of the list >>> len(list1)
5
2 max(list) It returns the item that has maximum >>> max(list1)
value in the list 8
3 sum(list) Calculates sum of all elements of list >>> sum(list)
18
4 min(list) It returns the item that has minimum >>> min(list)
value in the list 1
5 list(seq) It coverts a tuple into a list >>> tuple1=(45,68,62)
>>> list(tuple1)
[45, 68, 62]
Methods of List class
Sr. Methods Description Example
No. list1=[1 , 5, 3, 5, 8]
1 list.append(item) It adds the item to the end of the list >>> list1.append(9)
>>> list1
[1, 5, 3, 5, 8, 9]
2 list.count(item) It returns number of times the item occurs in the list >>> list1.count(5)
2
3 list.extend(seq) It adds the elements of the sequence at the end of the >>> list2=[“A”, “B”, “C”]
list >>> list1.extend(list2)
>>> list1
[1, 5, 3, 5, 8, ‘A’, ‘B’, ‘C’]
4 list.index(item) It returns the index number of the item. Returns lowest list1.index(5)
index if item appears more than once 1
5 list.insert(index, It inserts the given item onto the given index number >>> list1.insert(2,7)
item) while the elements in the list take one right shift >>> list1
[1, 5, 7, 3, 5, 8]
Sr. Methods Description Example
No. list1=[1 , 5, 3, 8, 5,9]

6 list.pop() It deletes and returns last element from the list >>> list1.pop()
9
list.pop(n) It deletes and returns element that is at nth index in the >>> list1.pop(2)
list 3
list.pop(-n) It deletes and returns nth element from the last of the >>> list1.pop(-2)
list 5
7 list.remove(item) It deletes the given item from the list. >>> list1.remove(3)
>>> list1
[1, 5, 8, 5, 9]
If item appears more than once, then item with lower >>> list1.remove(5)
index is removed. >>> list1
[1, 8, 5, 9]

8 list.reverse() It reverses the position (index number) of the items in >>> list1.reverse()
the list [9, 5, 8, 3, 5, 1]
9 list.sort() Sorts items from the list # ascending by default >>> list1.sort()
[1, 3, 5, 5, 8, 9]
10 list.sort(reverse= It sorts the elements inside the list and uses compare list.sort(key=len)
True|False, function if provided
key=myFunc)
list.sort() # list remains unchanged, returns sorted list
sorted(list) # list is sorted in place, original list is sorted
>>> strs = ['aa', 'BB', 'zz', 'CC']
>>> print(sorted(strs)) ## ['BB', 'CC', 'aa', 'zz'] (case sensitive)
>>> print(sorted(strs, reverse=True)) ## ['zz', 'aa', 'CC', 'BB']
>>> strs = ['ccc', 'aaaa', 'd', 'bb']
>>> print(sorted(strs, key=len)) ## ['d', 'bb', 'ccc', 'aaaa']
## "key" argument specifying str.lower function to use for sorting
>>> print(sorted(strs, key=str.lower)) ## ['aa', 'BB', 'CC', 'zz']
+ operator is used to combine lists:
>>> list1 = [10, 20, 30]
>>> list2 = [‘a’, ’b’]
>>> list1+list2
[10, 20, 30, ‘a’, ‘b’]
* operator is used to repeat the list:
>>> list2 * 2
[‘a’, ’b’, ’a’, ‘b]
>>> strs = ['ccc', 'aaaa', 'd', 'bb']
>>> print(sorted(strs, key=len)) ## ['d', 'bb',
'ccc', 'aaaa']
Tuples
• Linear and ordered data structure
• Tuples are unchangeable (immutable)
• Heterogeneous elements
Sr. Immutable (values cannot be modified) Mutable (values can be
No. modified)

Strings Tuples List


str = “hi” tuples = (5, 4.0, ‘a’) list = [5, 4.0, ‘a’]

1 Sequence Unicode character Ordered Sequence Ordered Sequence


2 Values cannot be modified Same as list but it is faster than Value can be changed
list because it is immutable dynamically

3 It is sequence of characters Values are stored in Values are stored in


alphanumeric alphanumeric
4 Access values from string Access values from tuple Access values from list
5 Adding values is not possible Adding values is not possible Adding values is possible
6 Removing values is not Removing values is not Removing values is possible
possible possible
Tuples
Creating >>> tuple1=(10, 20, 30)
tuple >>> tuple2= (10, “ab”, 23.87, ‘J’)
>>> tuple3=(“python”, [10,20,30], [11, “abs”, 23.56])
>>> tuple4=10, 20, 30.40 #tuple can be created without parenthesis
#In case, generating a tuple with a single element, make sure to add a
comma after the element otherwise it would not be considered as tuple
>>> tuple5=10
>>> type(tuple5)
<class ‘int’>
>>> tuple6 = (“hello”,)
>>> type (tuple6)
<class ‘tuple’>
tuple # No of variables in the tuple of left of assignment must match no of
assignment items in the tuple on the right of assignment
>>> vijay = (11, “Vijay”, “Raigad”)
>>> (id, name, city) = vijay
>>> print (id)
11
>>> print (name)
Vijay
swapping >>> x=10
the values >>> y=20
of two print (x, y)
variables 10 20
using tuple >>> x, y = y, x
assignment >>> print (x, y)
20 10
Accessing tuple=(10, 20, 30 ,40, 50)
values in a >>> tuple[1]
tuple 20
>>> tuple[1:4] # return values m to n-1 index
(20, 30 ,40)
>>> tuple[:2] # from 0 to m-1 index
10 20
>>> tuple[2:] # from m to last index
(30, 40, 50)
>>> tuple[-1] # access value at last index
50
Deleting # Tuples are unchangeable, so we can not remove item from it, but we can
tuples delete tuple completely
>>> del t1 # t1 = (10, 20) defined earlier
Traceback (most recent call last):
File “<pyshell#65>”, line 1, in <module>
t1
NameError: name ‘t1’ is not defined
Deleting an element # We can use index slicing to leave out a particular index
from a tuple >>> a = (1, 2, 3, 4)
>>> b = a[:2] + a[3:] # element 3 (at index 2 is left out]
>>> print b
(1, 2, 4) # output
delete/update # Or we can convert a tuple into list, remove the item and convert list back to tuple
(both operations are not >>> tuple1 = (1, 2, 3, 4)
allowed on tuple, but by >>> list1 = list(tuple1)
converting to list and >>> del list1[2]
back to tuple, we can >>> b = tuple(list1) # For Update
achieve it) >>> print (b) >>> list1[2] = 8
(1, 2, 4) >>> b = tuple(list1)
>>> print (b)
Updating a tuple, if its >>> tuple1 = (1, 2, 3, [4, 5]) (1, 2, 8, 4)
element itself is mutable >>> tuple1[3][0] = 14
>>> tuple1[3][1] = 15
>>> tuple1
(1, 2, 3, [14, 15])
Tuple operations
Concatenation >>> t1 = (10, 20)
>>> t2 = (30 ,40)
>>> t1 + t2
(10, 20, 30, 40)
Repetition >>> t1 * 3
(10, 20, 10, 20, 10, 20)
Membership function >>> 20 in t1
True
>>> 20 in t2
False
Iterating through a >>> t1 = (10, 20, 30)
tuple >>> for i in t1:
>>> print (i)
Output:
10
20
30
>>>
Built in functions and methods of tuple
Sr. no. Function/ Description Example
methods t1 = (1, 2, 4), t2=(‘a’, ’b’)
1 len(tuple) Returns the total length of the tuple (no of elements) >>> len(t1)
3
2 max(tuple) Returns largest value from the tuple >>> max(t1)
4
3 min(tuple) Returns the smallest value from the tuple >>> min(t1)
4 zip(tuple1 and It zips elements from two tuples into a list of tuples. >>> t3=zip(t1,t2)
tuple2) Length of the zipped tuple is decided by the smaller >>> list(t3)
length tuple. [(1, ‘a’), (2, ‘b’)]
5 tuple(seq) Converts a list into tuple >>> list1 = [11 ,22, 33]
>>> t = tuple(list1)
>>> t
(11 , 22, 33)
6 Method: Returns the number of times a specified value n occurs >>> t1.count(2)
count(n) in a tuple 1
7 Method: Searches the tuple for a specified value and returns the >>> t1.index(4)
index(item) position of where it was found 2
Sets
• Sets are unordered collection of unique items
• A set is a collection which is unordered, unchangeable*,
and unindexed.
* Note: Set items are unchangeable, but you can remove items and add new
items.
* It can contain any type of element such as integer, float, tuple etc. But
mutable elements (list, dictionary) can't be a member of set.
Accessing values in set
Create set with { } >>> a = {1, 3, 5, 4, 2}
>>> print (“a = “, a)
a = {1, 3, 5, 4, 2}
>>> print (type(a))
<class ‘set’>
>>> colors = {‘red’, green’, ‘blue’, ‘red’}
{‘blue’, ‘green’, ‘red’}
Create a set with set() >>> s = set(‘abc’)
constructor >>> s
{‘c’, ‘a’, ‘b’}
>>> s = set(range(1,3))
>>> s
{1, 2}
Deleting values in a set
>>> b = {10, 20, 30}
discard() method >>> b.discard(20)
>>> b
{10, 30}
>>> b.discard(20) # item not in the set, but does not raise an error
>>> b
{10, 30}
remove() method >>> b.remove(20)
Traceback most recent call list:
File ‘stdin’, line 1, in <module>
KeyError: 20
>>> b.remove(10)
>>> b
{30)
pop() method >>> b = {10, 20, 30}
>>> b.pop() # removes random element from set and returns it
30
clear() method >>> b.clear()
>>> b
set()
Updating Set
Using add() method. >>> a = {1, 2, 3}
>>> a.add(5)
Only one item at a time allowed to add. >>> a
{1, 2, 3, 5}
>>> a.add(4)
>>> a
{1, 2, 3, 4, 5}

Using update() method >>> a = {1, 2, 3}


Syntax: >>> b = (‘a’, ‘b’, ‘c’}
A.update(B) >>> a.update(b)
where B can be list/string/tuple/set and A is a >>> a
set which will be updated without duplicate {1, 2, 3, ‘b’, ‘a’, ‘c’}
entries
>>>a
{1,2,3,4,5, ’b’, ’a’, ’c’} # Suppose a is
this
>>>a.update({4, 6})
>>> a
{1, 2, 3, 4, 5, 6, ‘b’, ‘a’, ‘c’}
Basic Set Operations Example:
>>> A = {1, 2, 4, 6, 8}
>>> B = {1, 2, 3, 4, 5}
Union: Union of two sets is a set that consists of >>> C = A | B
all the items belonging to either set A or set B (or >>> C
both). {1, 2, 3, 4, 5, 6, 8} # No duplicate items
Intersection: Intersection of two sets is a set that >>> C = A & B
elements those are common to both sets. >>> C
{1, 2 ,4}
Difference: All the elements which are present in >>> C = A – B
set1 only but not in set2. >>> C
{6, 8}
Symmetric Difference: Symmetric difference of >>> C = A ^ B
two sets is a set that consists of all the items >>> C
belonging to either set A or set B but not in both. {3, 5, 6, 8}
Built-in functions and methods for Set
Sr. Methods Description Syntax
No.
1 union() Returns a new set containing set.union(set1,set2,…..)
the union of two or more sets
2 intersection() Returns a new set containing set.intersection(set1,set2,…….)
the intersection of two or more
sets
3 intersection_update() Removes the items from this set.
set those are not present in intersection_update(set1,set2,….)
other sets
4 difference() Returns a new set containing set.difference(set1,set2,…)
the difference between two or
more sets
5 difference_update() Removes the items from this set.difference_update(setr1,set2,
set that are also included in ….)
another sets
6 symmetric_difference() Returns a new set with the symmetric set.symmetric_differen
difference of two or more sets ce(set1,set2,…..)
7 symmetric_difference()_u Modify this set with symmetric difference of set.
pdate this set and other set symmetric_difference()_u
pdate(set1)
8 isdisjoint() Determine whether or not two sets have set.disjoint(set1)
any elements in common
9 issubset() Determine whether one set is subset of the set.issubset(set1)
other
10 issuperset() Determine whether one set is superset of set.issuperset(set1)
the other
11 add(item) It adds an item to the list. It has no effect if set.add(item)
an item is already in the set
12 discard(item) It removes the specified item from the set set.discard(item)
13 remove(item) Remove an item from the set; it mist be a set.remove(item)
member. If not a member, raise a KeyError.
14 pop() Remove and return an arbitrary item that is set.pop()
the last element of the set. Raises KeyError
if set is empty.
15 update() Updates the set with the union of the set set.update(set1)
and others(sets/iterables)
Sr. Built-in Description Example
No. function A = {3, 1, 6, 7}
1 all() Returns true if all the elements of the set(or >>> all (A)
iterable) are true or if the set is empty True
2 any() Returns True if any element of the set(or iterable) >>> any(A)
is true. If the set is empty, return False. True
3 len() Returns the length (no of items) in the list >>> len(A)
4
4 max() Returns the largest item in the set >>> max(A)
7
5 min() Returns the smallest item in the set >>> min(A)
1
6 sorted() Returns a new sorted list from elements in the set >>> sorted (A)
(does not sort the set itself) {1, 3, 6, 7)
>>> A
{3, 1, 6, 7}
7 sum() Returns the sum of all elements in the set >>> sum(A)
17
sorted() sort()

The sorted() function returns a sorted list of the specific


iterable object. The sort() method sorts the list.

We can specify ascending or descending order while using


the sorted() function It sorts the list in ascending order by default.

Its Syntax is : Its Syntax is :


sorted(iterable, key=key, reverse=reverse) list.sort(reverse=True|False, key=myFunc)

Its return type is a sorted list. We can also use it for sorting a list in descending order.

Does not modify the original iterable Modifies the original list in-place

Accepts additional parameters such as key and reverse for


customization Accepts key and reverse parameters directly

It can only sort a list that contains only one type of value. It sorts the list in-place.

Can handle different types of iterables Limited to lists, raises an error for other types

Compatible with any iterable Only applicable to lists

Can be used with strings for alphabetical sorting Directly applicable to lists of strings
Dictionaries
• Dictionary is a non-linear, unordered data structure used to store
key-value pairs indexed by keys. Keys are unique and keys can be
duplicate. Dictionaries are changeable(mutable). Dictionaries can be
nested.
• Syntax:
<dictionary_name> = {key1:value1, key2:value2,….,keyN:valueN}
Ex. emp = {“ID”:20, “Name”:”Amar”, “Gender”:”Male”, “Salary”:50}
Creating dictionary >>> dict1={}
>>> dict1
{}
>>> dict2 = {1:”Orange”, 2:”Mango”, 3:”Banana”}
>>> dict3 = {“name”:”Vijay”, 1:[10,20]}
creating dictionary using dict() >>> d1 = dict({1:”Orange”, 2:”Mango”, 3:”Banana”})
>>> d1
{1:”Orange”, 2:”Mango”, 3:”Banana”}
>>> d2 = dict([(1, “Red”), (2, “Yellow”), (3, “Green”)])
>>> d2
{1: 'Red', 2: 'Yellow', 3: 'Green'}
>>> d3 = dict(one=1, two=2, three=3)
>>> d3
{'one': 1, 'two': 2, 'three': 3}
Accessing values in a >>> dict3[‘name’]
dictionary: By referring to its ‘Vijay’
key name, inside square >>> d1[1]
brackets ([]) ‘Orange’
>>> d3[‘four’]
Traceback (most recent call last): # key is not in dictionary, so exception
File "<pyshell#12>", line 1, in <module> # This exception can be avoided,
d3['four'] # by using get() method
KeyError: 'four'
Using get() method returns >>> dict1 = {‘name’:’Vijay’, ‘age’:40}
the value for key if key is in >>> dict1.get(‘name’)
dictionary, else None, so that ‘Vijay’
this method never raises a >>> dict1.get(‘adr’)
KeyError # None returned
>>>
Deleting items from >>> squares = {1:1, 2:4, 3:9, 4:16, 5:25}
Dictionary >>> print(squares.popitem()) #remove and return arbitrary item
(5, 25)
>>> squares.pop(2) # remove an item with given key & return its value
4
>>> del squares[3] # remove item with given key, nothing returned
>>> squares
{1:1, 4:16}
>>> squares.clear() # removes all items, nothing returned, makes it empty
>>> squares
{}
>>> del squares # deletes a dictionary itself from the memory
>>> squares
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
squares
NameError: name ‘squares' is not defined
Updating dictionary: We can add new items or >>> dict1 = {‘name’:’Vijay’, ‘age’:40}
change the value of existing items. If key is >>> dict1[‘age’] = 35
already present, its value gets updated, else a >>> dict1
new key:value pair is added to the dictionary {‘name’:’Vijay’, ‘age’:35} #updating value
>>> dict1[‘address’] = ‘Lonere’
>>> dict1
{‘name’:’Vijay’, ‘age’:35, ‘address’:’Lonere’}
Basic operations on dictionary
1. Dictionary membership test: Using a keyword >>> print (‘name’ in dict1)
in, we can test if a key is in a dictionary or not. True
Not for values, only for keys. >>> print (‘adr’ in dict1)
False
>>> print(35 in dict1) # works for keys only
False
2. Traversing a dictionary: Output:
>>> squares 1 1
{1:1, 2:4, 3:9, 4:16, 5:25} 2 4
>>> for i in squares: 3 9
print (i, squares[i]) 4 16
5 25
Properties of dictionary keys: >>> dict = {1:’Vijay’, 2:’Amar’, 3:’Santosh’,
Dictionary values have no restrictions. They 2:’Umesh’}
can be any arbitrary python object, either >>> dict
standard objects or user-defined objects. {1:’Vijay’, 2:’Umesh’, 3:’Santosh’}
However, same is not true for keys.
1. More than one entry per key not allowed.
When duplicate keys are encountered during
assignment, the last assignment wins

2. Keys must be immutable. Which means >>> dict = {[1]:’Vijay’, 2:’Amar’, 3:’Santosh’}
you can use strings, numbers or tuples as Traceback (most recent call last):
dictionary keys but something like [‘key’] is File "<pyshell#3>", line 1, in <module>
not allowed dict = {[1]:'Vijay', 2:'Amar', 3:'Santosh'}
TypeError: unhashable type: 'list'
Built-in Functions and methods for dictionary
Sr. Method Description Example
No. >>> dict = {1:’Vijay’, 2:’Amar’, 3:’Santosh’}
1 clear() Removes all the elements from the >>> dict.clear()
dictionary >>> dict
{}
2 copy() Returns a copy of the dictionary >>> x=dict.copy()
>>> x
{1:’Vijay’, 2:’Amar’, 3:’Santosh’}
3 fromkeys() It creates a new dictionary with default >>>
value for all specified keys. If default dict=dict.fromkeys([‘Vijay’,’Meenakshi’],’Author’)
value is not specified, all keys are set to >>> dict
None. {'Vijay': 'Author', 'Meenakshi': 'Author'}
4 get() Returns the value of the specified key >>> dict1 = {‘name’:’Vijay’, ‘age’: 40}
>>> dict1.get(‘name’)
‘Vijay’
5 items() Returns a list containing the tuple for >>> for i in dict.items():
each key value pair print(i)
(1, ‘Vijay’)
(2, ‘Amar’)
(3, ‘Santosh’)
6 keys() Returns a list containing the dictionary’s >>> dict.keys()
keys dict_keys([1, 2, 3])
7 pop() Removes the element with the specified >>> print(dict.pop(2))
key ‘Amar’
8 popitem() Removes the last inserted key-value pair >>> dict.popitem()
(3, ‘Santosh’)
9 setdefault() Returns the value of the specified key. If >>> dict
the key does not exist; insert the key, {2:’Amar’, 3:’Santosh’}
with the specified value >>> dict.setdefault(1,’Vijay)
>>> dict
{2:’Amar’, 3:’Santosh’,1:’Vijay’}
10 update() Updates the dictionary with the >>> dict1={2:’Amar’, 4:’Santosh’}
specified key-value pairs. >>> dict2 ={1:’Vijay’, 3:’Umesh’}
>>> dict1.update(dict2)
>>> dict1
{2:’Amar’, 4:’Santosh’, 1:’Vijay’, 3:’Umesh’}
11 values() Returns a list of all the values in the >>> dict1.values()
dictionary dict_values([‘Amar’, ’Santosh’, ’Vijay’, ’Umesh])
Built-in functions of Dictionary
Sr. Function Description Example
No. >>> dict = {1:’Amar’, 2:’Vijay’, 3:’Santosh’}
1 all() Return True if all keys of the dictionary >>> all(dict)
are true (or if the dictionary is empty) True
2 any() Return True if any key of the dictionary >>> dict={}
is true. If the dictionary is empty, return >>> any(dict)
False False
3 len() Returns the length (no of items) in the >>> len(dict)
dictionary 3
4 sorted() Return a new sorted list of the keys in >>> dict1 = {2:’Amar’, 1:’Vijay’, 4:’Umesh’, 3:’Santosh’}
the dictionary >>> sorted(dict1)
[1, 2, 3, 4]
5 type() Returns the type of the passed variable >>> print(“Variable type: %s” %type (dict1))
Strings
• Strings are linear data structure in Python. It is a group of characters.
• Group of characters in the string are enclosed within set of single
quotes or double quotes.
• Python strings are immutable.
Function Example:
>>> a=“PYTHON”
>>> b=“Language”
len() function returns no o characters in a string >>> len(a)
6
min() function returns the smallest character in a >>> min(a)
string (Chronological order as per ASCII) ‘H’
max() function returns the largest character in a string >>> max(a)
(Chronological order as per ASCII) ‘Y’
deleting entire string >>> del a
>>> a
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
c
NameError: name ‘a' is not defined
String concatenation and multiplication >>> a + b
‘PYTHON Language’
>>> a*3
PYTHONPYTHONPYTHON
Traversing a string >>> for ch in a:
>>> index=0 print(ch,end=“”)
>>> while index < len(a) PYTHON
print(s[index], end=“”)
index = index+1
Strings are immutable >>> a[2]=‘z’
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
a[2]='z'
TypeError: 'str' object does not support item
assignment
‘in’ and ‘not in’ operator.
String slicing.
String comparison.
Special Characters in String
Sr. Escape Meaning Example
No. character
1 \n The new line character helps the programmer to >>> txt = “Guru\n99!”
insert a new line before or after a string. >>> print(txt)
Guru
99!
2 \\ This escape sequence allows the programmer to >>> txt = “Guru\\99!”
insert a backslash into the Python output. >>> print(txt)
Guru\99!

3 \xhh Use a backslash followed by a hexadecimal >>> txt = “\x47\x75\x72\x75” + “99!”


number. >>> print(txt)
This is done by printing in backslash with the Guru99!
hexadecimal equivalent in double quotes.

4 \ooo To get the integer value of an octal value, provide >>> txt = ‘\107\125\122\125’+ “99!”
a backslash followed by ooo or octal number in >>> print(txt)
double-quotes. GURU99!
It is done by printing in a backslash with three
octal equivalents in double quotes.
5 \b This escape sequence provides backspace to the Python >>> txt = “Guru\\99!”
string. It is inserted by adding a backslash followed by >>> print(txt)
“b”. Guru\99!
“b” here represents backslash.

6 \f It helps in the interpolation of literal strings >>> txt = “Guru\f99!”


>>> print(txt)
Guru99!

7 \r It helps you to create a raw string >>> txt = “Guru\r99!”


>>> print(txt)
Guru99!

8 \’ It helps you to add a single quotation to string >>> txt = “Guru\’99!”


>>> print(txt)
Guru99!

9 \t tab >>> txt = “Hello\tWorld”


>>> print (txt)
Hello World

You might also like