0% found this document useful (0 votes)
5 views38 pages

Python Unit-3 Notes (New)

Unit-3 of the BCS302 Python Programming course covers complex data types including strings, lists, tuples, and dictionaries. It provides an introduction to each data type, their operations, methods, and practical examples. The unit also includes a quick reference guide for string, list, and dictionary operations.

Uploaded by

shivandinesh4
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)
5 views38 pages

Python Unit-3 Notes (New)

Unit-3 of the BCS302 Python Programming course covers complex data types including strings, lists, tuples, and dictionaries. It provides an introduction to each data type, their operations, methods, and practical examples. The unit also includes a quick reference guide for string, list, and dictionary operations.

Uploaded by

shivandinesh4
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

Unit-3: Complex Data Types BCS302: Python Programming

1
Python Programming: Unit-3
Complex Data Types
BCS302 - AKTU University
Comprehensive Study Notes
3rd Semester

Academic Resource
AcademicArk - [Link]
Exam Preparation Material

2
Unit-3: Complex Data Types BCS302: Python Programming

Contents
1 String Data Type 5
1.1 Introduction to Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2 String Indexing and Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.1 String Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.2 String Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 String Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.1 Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.2 Repetition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3.3 Membership Testing . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4 String Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.5 String Manipulation Methods . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5.1 Case Conversion Methods . . . . . . . . . . . . . . . . . . . . . . 9
1.5.2 String Search and Replace Methods . . . . . . . . . . . . . . . . . 9
1.5.3 String Trimming Methods . . . . . . . . . . . . . . . . . . . . . . 10
1.5.4 String Splitting and Joining . . . . . . . . . . . . . . . . . . . . . 10
1.5.5 Character and Format Check Methods . . . . . . . . . . . . . . . 11
1.5.6 String Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2 List Data Type 12


2.1 Introduction to Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.2 List Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.3 List Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.4 List Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.4.1 Concatenation and Repetition . . . . . . . . . . . . . . . . . . . . 14
2.4.2 Membership and Length . . . . . . . . . . . . . . . . . . . . . . . 15
2.5 List Manipulation Methods . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.5.1 Adding Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.5.2 Removing Elements . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.5.3 Searching and Sorting . . . . . . . . . . . . . . . . . . . . . . . . 18
2.5.4 Other List Methods . . . . . . . . . . . . . . . . . . . . . . . . . . 19

3 Tuple Data Type 19


3.1 Introduction to Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.2 Tuple Indexing and Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.3 Tuple Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.3.1 Concatenation, Repetition, and Membership . . . . . . . . . . . . 21
3.3.2 Tuple Immutability . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.4 Tuple Methods and Functions . . . . . . . . . . . . . . . . . . . . . . . . 23

4 Dictionary Data Type 23


4.1 Introduction to Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.2 Accessing Dictionary Elements . . . . . . . . . . . . . . . . . . . . . . . . 24
4.3 Dictionary Modification . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.3.1 Adding and Updating Elements . . . . . . . . . . . . . . . . . . . 25
4.3.2 Removing Elements . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.4 Dictionary Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.5 Dictionary Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

3
Unit-3: Complex Data Types BCS302: Python Programming

5 Functions in Python 28
5.1 Introduction to Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 28
5.2 Function Parameters and Arguments . . . . . . . . . . . . . . . . . . . . 29
5.2.1 Types of Parameters . . . . . . . . . . . . . . . . . . . . . . . . . 29
5.2.2 Variable-Length Arguments . . . . . . . . . . . . . . . . . . . . . 31
5.3 Return Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.4 Practical Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.4.1 Example 1: Fibonacci Sequence . . . . . . . . . . . . . . . . . . . 33
5.4.2 Example 2: Palindrome Checker . . . . . . . . . . . . . . . . . . . 33
5.4.3 Example 3: Processing Lists and Dictionaries . . . . . . . . . . . 34

6 Comprehensive Programming Examples 35


6.1 Example 1: Student Information System . . . . . . . . . . . . . . . . . . 35
6.2 Example 2: Text Analysis Program . . . . . . . . . . . . . . . . . . . . . 36

7 Important Concepts Summary 37


7.1 Data Type Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
7.2 When to Use Each Data Type . . . . . . . . . . . . . . . . . . . . . . . . 37

8 Quick Reference Guide 37


8.1 String Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
8.2 List Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
8.3 Dictionary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

4
Unit-3: Complex Data Types BCS302: Python Programming

1 String Data Type


1.1 Introduction to Strings
Definition
A string is an immutable sequence of characters enclosed in single quotes (’’),
double quotes (""), or triple quotes (´´´ or """). Strings are one of the most
fundamental data types in Python.

Example

# Creating strings in different ways


str1 = ’ Hello World ’
str2 = " Python Programming "
str3 = ’ ’ ’ This is a multi - line
string using triple quotes ’ ’ ’
str4 = " " " Another multi - line
string format " " "

print ( str1 )
print ( str2 )
print ( str3 )

1.2 String Indexing and Slicing


1.2.1 String Indexing
Definition
String indexing allows accessing individual characters using their position. Python
uses zero-based indexing where the first character has index 0. Negative indexing
counts from the end of the string.

Important
Forward indexing: string[0] gives first character
Backward indexing: string[-1] gives last character

5
Unit-3: Complex Data Types BCS302: Python Programming

Example

text = " Python "


print ( text [0]) # Output : P
print ( text [3]) # Output : h
print ( text [ -1]) # Output : n ( last character )
print ( text [ -2]) # Output : o ( second last )

# Demonstrating indexing
# Index : 0 1 2 3 4 5
# String : P y t h o n
# Neg Index : -6 -5 -4 -3 -2 -1

Tip
If you try to access an index that doesn’t exist, Python will raise an IndexError
exception.

1.2.2 String Slicing


Definition
String slicing extracts a portion of a string using the syntax
string[start:end:step]. The slice includes the character at start but
excludes the character at end.

Example

text = " AcademicArk "

# Basic slicing
print ( text [0:7]) # Output : Academi
print ( text [7:11]) # Output : Ark
print ( text [:5]) # Output : Acade ( from start )
print ( text [6:]) # Output : Ark ( to end )
print ( text [:]) # Output : AcademicArk ( whole string )

# Slicing with step


print ( text [::2]) # Output : AaeicAk ( every 2 nd char )
print ( text [:: -1]) # Output : krAcimacadA ( reversed )
print ( text [1::2]) # Output : cdmcr ( from index 1 , every
2 nd )

# Negative slicing
print ( text [ -4:]) # Output : Ark
print ( text [: -3]) # Output : AcademicA

6
Unit-3: Complex Data Types BCS302: Python Programming

Important
Slicing does not raise an error even if indices are out of range. Python automatically
handles boundary conditions gracefully.

1.3 String Operations


1.3.1 Concatenation
Definition
String concatenation combines two or more strings into a single string using the +
operator.

Example

str1 = " Hello "


str2 = " World "
result = str1 + " " + str2
print ( result ) # Output : Hello World

# Multiple concatenation
greeting = " Hi " + " " + " there " + " ! "
print ( greeting ) # Output : Hi there !

1.3.2 Repetition
Definition
String repetition creates a new string by repeating the original string multiple times
using the * operator.

Example

text = " Ha "


print ( text * 3) # Output : HaHaHa

symbol = " -"


print ( symbol * 10) # Output : - - - - - - - - - -

line = " * " * 5


print ( line ) # Output : * * * * *

7
Unit-3: Complex Data Types BCS302: Python Programming

1.3.3 Membership Testing


Definition
The in operator checks if a substring exists within a string, returning True or
False.

Example

text = " Python Programming "

print ( " Python " in text ) # Output : True


print ( " Java " in text ) # Output : False
print ( " Pro " in text ) # Output : True
print ( " xyz " in text ) # Output : False

# Using not in operator


print ( " Java " not in text ) # Output : True

1.4 String Comparison


Definition
Strings can be compared using comparison operators (==, !=, <, >, <=, >=) based
on lexicographical order (dictionary order).

Example

str1 = " apple "


str2 = " banana "
str3 = " apple "

print ( str1 == str3 ) # Output : True


print ( str1 != str2 ) # Output : True
print ( str1 < str2 ) # Output : True ( a < b
lexi cograp hicall y )
print ( " Z " > " A " ) # Output : True
print ( " dog " >= " cat " ) # Output : True

8
Unit-3: Complex Data Types BCS302: Python Programming

1.5 String Manipulation Methods


1.5.1 Case Conversion Methods
Example

text = " Python Programming "

# Convert to uppercase
print ( text . upper () ) # PYTHON PROGRAMMING

# Convert to lowercase
print ( text . lower () ) # python programming

# Title case ( capitalize each word )


print ( text . title () ) # Python Programming

# Capitalize first character only


print ( text . capitalize () ) # Python programming

# Swap case
print ( " AbCd " . swapcase () ) # aBcD

1.5.2 String Search and Replace Methods


Example

text = " Hello World , Hello Python "

# Find method - returns index of first occurrence


print ( text . find ( " Hello " ) ) # Output : 0
print ( text . find ( " World " ) ) # Output : 6
print ( text . find ( " Java " ) ) # Output : -1 ( not found )

# Index method - similar to find , but raises error if not


found
print ( text . index ( " Hello " ) ) # Output : 0

# Count method - counts occurrences


print ( text . count ( " Hello " ) ) # Output : 2

# Replace method - replaces all occurrences


result = text . replace ( " Hello " , " Hi " )
print ( result ) # Hi World , Hi Python

# Replace with limit


result = text . replace ( " Hello " , " Hi " , 1) # Replace only first
print ( result ) # Hi World , Hello Python

9
Unit-3: Complex Data Types BCS302: Python Programming

1.5.3 String Trimming Methods


Example

text = " Python Programming "

# Remove leading and trailing spaces


print ( text . strip () ) # Python Programming

# Remove only leading spaces


print ( text . lstrip () ) # Python Programming

# Remove only trailing spaces


print ( text . rstrip () ) # ’ Python Programming ’

# Remove specific characters


text2 = " *** Python *** "
print ( text2 . strip ( " * " ) ) # Python

1.5.4 String Splitting and Joining


Example

# Split method - converts string to list


text = " Python Programming Language "
words = text . split () # Splits by space
print ( words ) # [ ’ Python ’, ’
Programming ’, ’ Language ’]

text2 = " apple , banana , orange "


fruits = text2 . split ( " ," ) # Splits by comma
print ( fruits ) # [ ’ apple ’, ’ banana ’,
’ orange ’]

# Join method - converts list to string


words = [ " Hello " , " World " , " Python " ]
sentence = " " . join ( words )
print ( sentence ) # Hello World Python

fruits = [ " apple " , " banana " , " orange " ]
result = " -" . join ( fruits )
print ( result ) # apple - banana - orange

10
Unit-3: Complex Data Types BCS302: Python Programming

1.5.5 Character and Format Check Methods


Example

# Check if string is alphanumeric


print ( " Python123 " . isalnum () ) # True
print ( " Python 123 " . isalnum () ) # False

# Check if all characters are alphabetic


print ( " Python " . isalpha () ) # True
print ( " Python123 " . isalpha () ) # False

# Check if all characters are digits


print ( " 12345 " . isdigit () ) # True
print ( " 123 ab " . isdigit () ) # False

# Check if string is lowercase / uppercase


print ( " python " . islower () ) # True
print ( " PYTHON " . isupper () ) # True

# Check if string is whitespace


print ( " " . isspace () ) # True
print ( " a " . isspace () ) # False

1.5.6 String Formatting


Example

# Using % operator ( old style )


name = " Python "
version = 3.10
print ( " Language : %s , Version : %.2 f " % ( name , version ) )

# Using format () method


print ( " Hello {} from {} " . format ( " Nikhil " , " Greater Noida " ) )

# Using f - strings ( Python 3.6+)


subject = " Python "
exam = " GATE "
print ( f " Preparing { subject } for { exam } " )

# Format with placeholders


print ( " {1} {0} " . format ( " Python " , " Programming " ) ) #
Programming Python

# Format with variables


print ( " { name } scored { marks } " . format ( name = " Nikhil " , marks =95)
)

11
Unit-3: Complex Data Types BCS302: Python Programming

2 List Data Type


2.1 Introduction to Lists
Definition
A list is an ordered, mutable (changeable) collection of elements enclosed in square
brackets []. Lists can contain elements of different data types and are the most
versatile data structure in Python.

Example

# Creating lists
list1 = [1 , 2 , 3 , 4 , 5]
list2 = [ " apple " , " banana " , " orange " ]
list3 = [1 , " Python " , 3.14 , True , None ] # Mixed types
list4 = [] # Empty list
list5 = [1 , [2 , 3] , 4] # Nested list

print ( list1 )
print ( list2 )
print ( list3 )
print ( list4 )

2.2 List Indexing


Definition
Lists support indexing similar to strings. Each element has a position, with zero-
based indexing for forward access and negative indexing for backward access.

12
Unit-3: Complex Data Types BCS302: Python Programming

Example

fruits = [ " apple " , " banana " , " orange " , " mango " , " grape " ]

# Forward indexing
print ( fruits [0]) # Output : apple
print ( fruits [2]) # Output : orange
print ( fruits [4]) # Output : grape

# Backward indexing
print ( fruits [ -1]) # Output : grape
print ( fruits [ -2]) # Output : mango
print ( fruits [ -5]) # Output : apple

# Accessing nested elements


nested = [1 , [2 , 3 , 4] , 5]
print ( nested [1][0]) # Output : 2
print ( nested [1][2]) # Output : 4

2.3 List Slicing


Definition
List slicing extracts a contiguous portion of a list using the syntax
list[start:end:step]. This creates a new list without modifying the original.

13
Unit-3: Complex Data Types BCS302: Python Programming

Example

numbers = [0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9]

# Basic slicing
print ( numbers [2:5]) # Output : [2 , 3, 4]
print ( numbers [:4]) # Output : [0 , 1, 2 , 3]
print ( numbers [6:]) # Output : [6 , 7, 8 , 9]
print ( numbers [:]) # Output : [0 , 1, 2, 3, 4, 5, 6,
7 , 8 , 9]

# Slicing with step


print ( numbers [::2]) # Output : [0 , 2 , 4 , 6 , 8]
print ( numbers [1::2]) # Output : [1 , 3 , 5 , 7 , 9]
print ( numbers [::3]) # Output : [0 , 3 , 6 , 9]

# Negative slicing
print ( numbers [ -5:]) # Output : [5 , 6 , 7 , 8 , 9]
print ( numbers [: -3]) # Output : [0 , 1 , 2 , 3 , 4 , 5 , 6]

# Reverse using slice


print ( numbers [:: -1]) # Output : [9 , 8 , 7 , 6 , 5 , 4 , 3 ,
2 , 1 , 0]

2.4 List Operations


2.4.1 Concatenation and Repetition
Example

# Concatenation
list1 = [1 , 2 , 3]
list2 = [4 , 5 , 6]
result = list1 + list2
print ( result ) # Output : [1 , 2 , 3 , 4 , 5 , 6]

# Multiple concatenation
combined = [1] + [2] + [3]
print ( combined ) # Output : [1 , 2 , 3]

# Repetition
list3 = [1 , 2] * 3
print ( list3 ) # Output : [1 , 2 , 1 , 2 , 1 , 2]

# String repetition in list


list4 = [ " a " ] * 4
print ( list4 ) # Output : [ ’ a ’, ’a ’, ’a ’, ’a ’]

14
Unit-3: Complex Data Types BCS302: Python Programming

2.4.2 Membership and Length


Example

fruits = [ " apple " , " banana " , " orange " ]

# Check membership
print ( " apple " in fruits ) # Output : True
print ( " mango " in fruits ) # Output : False
print ( " banana " not in fruits ) # Output : False

# Get length
print ( len ( fruits ) ) # Output : 3

# Length of nested list


nested = [1 , [2 , 3 , 4] , 5]
print ( len ( nested ) ) # Output : 3 ( not 5!)

2.5 List Manipulation Methods


2.5.1 Adding Elements
Definition
Methods to add elements to a list modify the list in-place and return None.

15
Unit-3: Complex Data Types BCS302: Python Programming

Example

# append () - adds element at end


list1 = [1 , 2 , 3]
list1 . append (4)
print ( list1 ) # Output : [1 , 2 , 3 , 4]

# insert () - adds element at specific index


list2 = [1 , 2 , 4]
list2 . insert (2 , 3) # Insert 3 at index 2
print ( list2 ) # Output : [1 , 2 , 3 , 4]

# extend () - adds multiple elements


list3 = [1 , 2 , 3]
list3 . extend ([4 , 5 , 6])
print ( list3 ) # Output : [1 , 2 , 3 , 4 , 5 , 6]

# Difference between append and extend


list4 = [1 , 2]
list4 . append ([3 , 4]) # Adds list as single element
print ( list4 ) # Output : [1 , 2 , [3 , 4]]

list5 = [1 , 2]
list5 . extend ([3 , 4]) # Adds individual elements
print ( list5 ) # Output : [1 , 2 , 3 , 4]

16
Unit-3: Complex Data Types BCS302: Python Programming

2.5.2 Removing Elements


Example

# remove () - removes first occurrence


list1 = [1 , 2 , 3 , 2 , 4]
list1 . remove (2)
print ( list1 ) # Output : [1 , 3 , 2 , 4]

# pop () - removes and returns element at index


list2 = [1 , 2 , 3 , 4 , 5]
removed = list2 . pop () # Removes last element
print ( list2 ) # Output : [1 , 2 , 3 , 4]
print ( removed ) # Output : 5

removed = list2 . pop (1) # Removes element at index 1


print ( list2 ) # Output : [1 , 3 , 4]
print ( removed ) # Output : 2

# clear () - removes all elements


list3 = [1 , 2 , 3 , 4 , 5]
list3 . clear ()
print ( list3 ) # Output : []

# del statement - removes by index or slice


list4 = [1 , 2 , 3 , 4 , 5]
del list4 [2]
print ( list4 ) # Output : [1 , 2 , 4 , 5]

del list4 [1:3] # Delete slice


print ( list4 ) # Output : [1 , 5]

17
Unit-3: Complex Data Types BCS302: Python Programming

2.5.3 Searching and Sorting


Example

# index () - finds first occurrence


list1 = [1 , 2 , 3 , 2 , 4]
print ( list1 . index (2) ) # Output : 1
print ( list1 . index (4) ) # Output : 4

# count () - counts occurrences


list2 = [1 , 2 , 2 , 3 , 2 , 4]
print ( list2 . count (2) ) # Output : 3
print ( list2 . count (5) ) # Output : 0

# sort () - sorts in - place


list3 = [3 , 1 , 4 , 1 , 5 , 9]
list3 . sort ()
print ( list3 ) # Output : [1 , 1 , 3 , 4 , 5 , 9]

# sort () with reverse


list4 = [3 , 1 , 4 , 1 , 5]
list4 . sort ( reverse = True )
print ( list4 ) # Output : [5 , 4 , 3 , 1 , 1]

# sorted () - returns new sorted list


list5 = [3 , 1 , 4 , 1 , 5]
sorted_list = sorted ( list5 )
print ( sorted_list ) # Output : [1 , 1 , 3 , 4 , 5]
print ( list5 ) # Output : [3 , 1 , 4 , 1 , 5] (
unchanged )

# Sort strings
fruits = [ " banana " , " apple " , " orange " ]
fruits . sort ()
print ( fruits ) # Output : [ ’ apple ’, ’ banana ’, ’
orange ’]

18
Unit-3: Complex Data Types BCS302: Python Programming

2.5.4 Other List Methods


Example

# reverse () - reverses in - place


list1 = [1 , 2 , 3 , 4 , 5]
list1 . reverse ()
print ( list1 ) # Output : [5 , 4 , 3 , 2 , 1]

# copy () - creates shallow copy


list2 = [1 , 2 , 3]
list2_copy = list2 . copy ()
list2 . append (4)
print ( list2 ) # Output : [1 , 2 , 3 , 4]
print ( list2_copy ) # Output : [1 , 2 , 3]

# Using slicing to copy


list3 = [1 , 2 , 3]
list3_copy = list3 [:]
print ( list3_copy ) # Output : [1 , 2 , 3]

# max () and min () - built - in functions


numbers = [5 , 2 , 8 , 1 , 9]
print ( max ( numbers ) ) # Output : 9
print ( min ( numbers ) ) # Output : 1

3 Tuple Data Type


3.1 Introduction to Tuples
Definition
A tuple is an ordered, immutable (unchangeable) collection of elements enclosed
in parentheses (). Once created, tuples cannot be modified. They are often used
when you need to protect data from accidental modification.

19
Unit-3: Complex Data Types BCS302: Python Programming

Example

# Creating tuples
tuple1 = (1 , 2 , 3 , 4 , 5)
tuple2 = ( " apple " , " banana " , " orange " )
tuple3 = (1 , " Python " , 3.14 , True ) # Mixed types
tuple4 = () # Empty tuple
tuple5 = (1 ,) # Single element ( note
comma )
tuple6 = 1 , 2 , 3 # No parentheses needed

# Accessing tuple elements


print ( tuple1 )
print ( tuple2 [0]) # Output : apple
print ( tuple3 [ -1]) # Output : True

Important
To create a single-element tuple, you must include a comma after the element:
(1,). Without the comma, (1) is just a regular integer in parentheses, not a
tuple.

3.2 Tuple Indexing and Slicing


Definition
Tuples support the same indexing and slicing operations as lists and strings. Both
forward and negative indexing are available.

20
Unit-3: Complex Data Types BCS302: Python Programming

Example

colors = ( " red " , " green " , " blue " , " yellow " , " purple " )

# Indexing
print ( colors [0]) # Output : red
print ( colors [2]) # Output : blue
print ( colors [ -1]) # Output : purple
print ( colors [ -3]) # Output : blue

# Slicing
print ( colors [1:4]) # Output : ( ’ green ’, ’ blue ’, ’
yellow ’)
print ( colors [:3]) # Output : ( ’ red ’, ’ green ’, ’ blue
’)
print ( colors [2:]) # Output : ( ’ blue ’, ’ yellow ’, ’
purple ’)
print ( colors [::2]) # Output : ( ’ red ’, ’ blue ’, ’ purple
’)
print ( colors [:: -1]) # Output : ( ’ purple ’, ’ yellow ’, ’
blue ’, ’ green ’, ’ red ’)

3.3 Tuple Operations


3.3.1 Concatenation, Repetition, and Membership
Example

# Concatenation
tuple1 = (1 , 2 , 3)
tuple2 = (4 , 5 , 6)
result = tuple1 + tuple2
print ( result ) # Output : (1 , 2 , 3 , 4 , 5 , 6)

# Repetition
tuple3 = ( " a " , " b " ) * 3
print ( tuple3 ) # Output : ( ’ a ’, ’b ’, ’a ’, ’b ’, ’a
’, ’b ’)

# Membership testing
colors = ( " red " , " green " , " blue " )
print ( " red " in colors ) # Output : True
print ( " yellow " in colors ) # Output : False

# Length and iteration


print ( len ( colors ) ) # Output : 3
for color in colors :
print ( color ) # Prints each color on new line

21
Unit-3: Complex Data Types BCS302: Python Programming

3.3.2 Tuple Immutability


Definition
Tuples are immutable, meaning you cannot change, add, or remove elements after
creation. Attempting to do so raises a TypeError.

Example

tuple1 = (1 , 2 , 3)

# This will raise an error :


# tuple1 [0] = 10 # TypeError : ’ tuple ’ object does not
support item assignment
# tuple1 . append (4) # AttributeError : ’ tuple ’ object has no
attribute ’ append ’

# However , mutable elements within tuples can be modified


tuple_with_list = (1 , [2 , 3 , 4] , 5)
tuple_with_list [1][0] = 20 # Modify the list inside
print ( tuple_with_list ) # Output : (1 , [20 , 3 , 4] , 5)

22
Unit-3: Complex Data Types BCS302: Python Programming

3.4 Tuple Methods and Functions


Example

# count () - counts occurrences


tuple1 = (1 , 2 , 2 , 3 , 2 , 4)
print ( tuple1 . count (2) ) # Output : 3
print ( tuple1 . count (5) ) # Output : 0

# index () - finds first occurrence


tuple2 = ( " apple " , " banana " , " orange " )
print ( tuple2 . index ( " banana " ) ) # Output : 1

# max () , min () , sum () - built - in functions


numbers = (5 , 2 , 8 , 1 , 9)
print ( max ( numbers ) ) # Output : 9
print ( min ( numbers ) ) # Output : 1
print ( sum ( numbers ) ) # Output : 25

# Tuple unpacking
tuple3 = (10 , 20 , 30)
a , b , c = tuple3
print (a , b , c ) # Output : 10 20 30

# Unpacking with *
tuple4 = (1 , 2 , 3 , 4 , 5)
first , * middle , last = tuple4
print ( first ) # Output : 1
print ( middle ) # Output : [2 , 3 , 4]
print ( last ) # Output : 5

4 Dictionary Data Type


4.1 Introduction to Dictionaries
Definition
A dictionary is an unordered, mutable collection of key-value pairs enclosed in curly
braces {}. Each key must be unique and immutable, while values can be of any
data type.

23
Unit-3: Complex Data Types BCS302: Python Programming

Example

# Creating dictionaries
dict1 = { " name " : " Nikhil " , " age " : 20 , " city " : " Greater Noida "
}
dict2 = {1: " one " , 2: " two " , 3: " three " }
dict3 = { " course " : " Python " , " level " : " Intermediate " , " marks "
: 95}
dict4 = {} # Empty dictionary

# Using dict () constructor


dict5 = dict ( name = " Python " , version =3.10)

# Accessing values
print ( dict1 [ " name " ]) # Output : Nikhil
print ( dict2 [1]) # Output : one

4.2 Accessing Dictionary Elements


Definition
Dictionary values are accessed using their keys. Using a key that doesn’t exist
raises a KeyError, but the .get() method provides a safer alternative.

Example

student = { " name " : " Nikhil " , " age " : 20 , " course " : " CSE " , "
cgpa " : 8.5}

# Direct access
print ( student [ " name " ]) # Output : Nikhil
print ( student [ " age " ]) # Output : 20

# Using get () method - safer


print ( student . get ( " name " ) ) # Output : Nikhil
print ( student . get ( " email " ) ) # Output : None ( no error )

# Using get () with default value


print ( student . get ( " email " , " Not provided " ) ) # Output : Not
provided

# Check if key exists


print ( " name " in student ) # Output : True
print ( " email " in student ) # Output : False

24
Unit-3: Complex Data Types BCS302: Python Programming

4.3 Dictionary Modification


4.3.1 Adding and Updating Elements
Example

student = { " name " : " Nikhil " , " age " : 20}

# Add new key - value pair


student [ " course " ] = " CSE "
student [ " city " ] = " Greater Noida "
print ( student )
# Output : { ’ name ’: ’ Nikhil ’, ’ age ’: 20 , ’ course ’: ’ CSE ’, ’
city ’: ’ Greater Noida ’}

# Update existing value


student [ " age " ] = 21
print ( student [ " age " ]) # Output : 21

# Using update () method


student . update ({ " cgpa " : 8.5 , " semester " : 5})
print ( student )
# Output : { ’ name ’: ’ Nikhil ’, ’ age ’: 21 , ’ course ’: ’ CSE ’, ’
city ’: ’ Greater Noida ’, ’ cgpa ’: 8.5 , ’ semester ’: 5}

# Using update () with another dictionary


new_info = { " email " : " nikhil@example . com " , " phone " : "
9876543210 " }
student . update ( new_info )
print ( student )

25
Unit-3: Complex Data Types BCS302: Python Programming

4.3.2 Removing Elements


Example

student = { " name " : " Nikhil " , " age " : 20 , " course " : " CSE " , "
cgpa " : 8.5}

# Using del
del student [ " cgpa " ]
print ( student ) # cgpa removed

# Using pop () - removes and returns value


removed = student . pop ( " age " )
print ( removed ) # Output : 20
print ( student )

# pop () with default value


removed = student . pop ( " email " , " Not found " )
print ( removed ) # Output : Not found

# Using popitem () - removes arbitrary key - value pair


removed_item = student . popitem ()
print ( removed_item )

# Using clear () - removes all elements


dict1 = { " a " : 1 , " b " : 2}
dict1 . clear ()
print ( dict1 ) # Output : {}

26
Unit-3: Complex Data Types BCS302: Python Programming

4.4 Dictionary Iteration


Example

student = { " name " : " Nikhil " , " age " : 20 , " course " : " CSE " }

# Iterate over keys


for key in student :
print ( key )
# Output : name , age , course

# Iterate over keys explicitly


for key in student . keys () :
print ( key )

# Iterate over values


for value in student . values () :
print ( value )
# Output : Nikhil , 20 , CSE

# Iterate over key - value pairs


for key , value in student . items () :
print ( f " { key }: { value } " )
# Output :
# name : Nikhil
# age : 20
# course : CSE

27
Unit-3: Complex Data Types BCS302: Python Programming

4.5 Dictionary Methods


Example

student = { " name " : " Nikhil " , " age " : 20 , " course " : " CSE " }

# keys () - returns all keys


all_keys = student . keys ()
print ( all_keys ) # dict_keys ([ ’ name ’, ’ age ’, ’
course ’])

# values () - returns all values


all_values = student . values ()
print ( all_values ) # dict_values ([ ’ Nikhil ’, 20 , ’ CSE
’])

# items () - returns key - value pairs


all_items = student . items ()
print ( all_items )
# dict_items ([( ’ name ’, ’ Nikhil ’) , ( ’ age ’, 20) , ( ’ course ’, ’
CSE ’) ])

# copy () - creates shallow copy


student_copy = student . copy ()
student_copy [ " age " ] = 21
print ( student [ " age " ]) # Output : 20 ( original unchanged )
print ( student_copy [ " age " ]) # Output : 21

# setdefault () - gets value or sets if key doesn ’t exist


print ( student . setdefault ( " age " , 25) ) # Output : 20 ( key
exists )
print ( student . setdefault ( " cgpa " , 8.5) ) # Output : 8.5 ( key
added )

# len () - number of key - value pairs


print ( len ( student ) ) # Output : 4

5 Functions in Python
5.1 Introduction to Functions
Definition
A function is a reusable block of code that performs a specific task. Functions
help organize code, promote reusability, and make programs more maintainable.
Functions are defined using the def keyword.

28
Unit-3: Complex Data Types BCS302: Python Programming

Example

# Basic function definition and call


def greet () :
print ( " Hello , Welcome to Python ! " )

# Call the function


greet () # Output : Hello , Welcome to Python !

# Function with parameters


def greet_person ( name ) :
print ( f " Hello , { name }! " )

greet_person ( " Nikhil " ) # Output : Hello , Nikhil !

# Function with return value


def add_numbers (a , b ) :
return a + b

result = add_numbers (5 , 3)
print ( result ) # Output : 8

5.2 Function Parameters and Arguments


5.2.1 Types of Parameters
Definition
Parameters are variables in function definitions. When you call a function with
values, those values are called arguments. Python supports different types of pa-
rameters: positional, default, keyword, and variable-length.

29
Unit-3: Complex Data Types BCS302: Python Programming

Example

# Positional parameters
def introduce ( name , age ) :
print ( f " Name : { name } , Age : { age } " )

introduce ( " Nikhil " , 20) # Arguments must match order

# Default parameters
def greet ( name = " Guest " ) :
print ( f " Hello , { name }! " )

greet () # Output : Hello , Guest !


greet ( " Nikhil " ) # Output : Hello , Nikhil !

# Keyword arguments
def display_info ( name , age , city ) :
print ( f " { name } is { age } years old and lives in { city } " )

display_info ( age =20 , city = " Greater Noida " , name = " Nikhil " )
# Output : Nikhil is 20 years old and lives in Greater Noida

30
Unit-3: Complex Data Types BCS302: Python Programming

5.2.2 Variable-Length Arguments


Example

# * args - variable number of positional arguments


def sum_numbers (* args ) :
total = 0
for num in args :
total += num
return total

print ( sum_numbers (1 , 2 , 3) ) # Output : 6


print ( sum_numbers (1 , 2 , 3 , 4 , 5) ) # Output : 15

# ** kwargs - variable number of keyword arguments


def print_info (** kwargs ) :
for key , value in kwargs . items () :
print ( f " { key }: { value } " )

print_info ( name = " Nikhil " , age =20 , city = " Greater Noida " )
# Output :
# name : Nikhil
# age : 20
# city : Greater Noida

# Combining all types


def complet e_func tion ( pos1 , pos2 , * args , key1 = None , ** kwargs )
:
print ( f " Positional : { pos1 } , { pos2 } " )
print ( f " Args : { args } " )
print ( f " Key1 : { key1 } " )
print ( f " Kwargs : { kwargs } " )

complete_ functi on (1 , 2 , 3 , 4 , key1 = " value1 " , extra = "


extra_value " )

5.3 Return Statements


Definition
The return statement sends a value back from a function to the caller. If no return
statement is specified, the function returns None.

31
Unit-3: Complex Data Types BCS302: Python Programming

Example

# Simple return
def multiply (a , b ) :
return a * b

result = multiply (5 , 3)
print ( result ) # Output : 15

# Multiple return values ( returns a tuple )


def get_min_max ( numbers ) :
return min ( numbers ) , max ( numbers )

numbers = [3 , 1 , 4 , 1 , 5 , 9]
minimum , maximum = get_min_max ( numbers )
print ( f " Min : { minimum } , Max : { maximum } " )
# Output : Min : 1 , Max : 9

# Early return
def check_positive ( num ) :
if num <= 0:
return " Not positive "
return " Positive "

print ( check_positive (5) ) # Output : Positive


print ( check_positive ( -3) ) # Output : Not positive

32
Unit-3: Complex Data Types BCS302: Python Programming

5.4 Practical Examples


5.4.1 Example 1: Fibonacci Sequence
Example

def fibonacci ( n ) :
" " " Generate Fibonacci sequence up to n terms " " "
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0 , 1]

fib_sequence = [0 , 1]
for i in range (2 , n ) :
fib_sequence . append ( fib_sequence [ -1] + fib_sequence
[ -2])
return fib_sequence

print ( fibonacci (7) )


# Output : [0 , 1 , 1 , 2 , 3 , 5 , 8]

5.4.2 Example 2: Palindrome Checker


Example

def is_palindrome ( text ) :


" " " Check if a string is a palindrome " " "
# Remove spaces and convert to lowercase
cleaned = text . replace ( " " , " " ) . lower ()
# Compare with reversed string
return cleaned == cleaned [:: -1]

print ( is_palindrome ( " A man a plan a canal Panama " ) ) # Output


: True
print ( is_palindrome ( " Hello " ) ) #
Output : False

33
Unit-3: Complex Data Types BCS302: Python Programming

5.4.3 Example 3: Processing Lists and Dictionaries


Example

# Function to filter students with CGPA > threshold


def fi l t e r _ h i g h _ p e r f o r m e r s ( students , threshold ) :
" " " Returns list of students with CGPA above threshold " " "
high_performers = []
for student in students :
if student [ " cgpa " ] >= threshold :
high_performers . append ( student )
return high_performers

students = [
{ " name " : " Nikhil " , " cgpa " : 8.5} ,
{ " name " : " Priya " , " cgpa " : 7.8} ,
{ " name " : " Rahul " , " cgpa " : 8.9} ,
{ " name " : " Anjali " , " cgpa " : 7.2}
]

top_students = f i l t e r _ h i g h _ p e r f o r m e r s ( students , 8.0)


for student in top_students :
print ( student )
# Output :
# { ’ name ’: ’ Nikhil ’, ’ cgpa ’: 8.5}
# { ’ name ’: ’ Rahul ’, ’ cgpa ’: 8.9}

34
Unit-3: Complex Data Types BCS302: Python Programming

6 Comprehensive Programming Examples


6.1 Example 1: Student Information System
Example

def create_student ( name , roll_no , subjects ) :


" " " Create a student dictionary " " "
return {
" name " : name ,
" roll_no " : roll_no ,
" subjects " : subjects ,
" marks " : {}
}

def add_marks ( student , subject , marks ) :


" " " Add marks for a subject " " "
if subject in student [ " subjects " ]:
student [ " marks " ][ subject ] = marks
else :
print ( f " Subject { subject } not found " )

def calcula te_ave rage ( student ) :


" " " Calculate average marks " " "
if not student [ " marks " ]:
return 0
total = sum ( student [ " marks " ]. values () )
return total / len ( student [ " marks " ])

def display_student ( student ) :


" " " Display student information " " "
print ( f " Name : { student [ ’ name ’]} " )
print ( f " Roll No : { student [ ’ roll_no ’]} " )
print ( f " Subjects : { ’ , ’. join ( student [ ’ subjects ’]) } " )
print ( f " Marks : { student [ ’ marks ’]} " )
print ( f " Average : { calcu late_a verage ( student ) :.2 f } " )

# Usage
nikhil = create_student ( " Nikhil " , 101 , [ " Python " , " DSA " , "
DBMS " ])
add_marks ( nikhil , " Python " , 95)
add_marks ( nikhil , " DSA " , 88)
add_marks ( nikhil , " DBMS " , 92)
display_student ( nikhil )

35
Unit-3: Complex Data Types BCS302: Python Programming

6.2 Example 2: Text Analysis Program


Example

def analyze_text ( text ) :


" " " Analyze text and return statistics " " "

# Convert to lowercase
text_lower = text . lower ()

# Count words
words = text . split ()
word_count = len ( words )

# Count characters
char_count = len ( text )
cha r _ co u n t_ n o _s p a ce = len ( text . replace ( " " , " " ) )

# Count sentences ( simple approach )


sentences = text . split ( " . " )
sentence_count = len ([ s for s in sentences if s . strip () ])

# Find longest and shortest word


longest_word = max ( words , key = len ) if words else " "
shortest_word = min ( words , key = len ) if words else " "

# Return results as dictionary


return {
" words " : word_count ,
" characters " : char_count ,
" c h a ra c t er s _ no _ s pa c e " : char_count_no_space ,
" sentences " : sentence_count ,
" longest_word " : longest_word ,
" shortest_word " : shortest_word ,
" avg_word_length " : c h a r_ c o un t _ no _ s pa c e / word_count
if word_count > 0 else 0
}

# Usage
text = " Python is a powerful programming language . It is
widely used in data science . "
results = analyze_text ( text )

for key , value in results . items () :


if isinstance ( value , float ) :
print ( f " { key }: { value :.2 f } " )
else :
print ( f " { key }: { value } " )

36
Unit-3: Complex Data Types BCS302: Python Programming

7 Important Concepts Summary


7.1 Data Type Comparison
Important
Strings: Immutable, ordered sequences of characters. Support indexing, slicing,
concatenation.
Lists: Mutable, ordered collections. Support all operations (add, remove, modify).
Most flexible.
Tuples: Immutable, ordered collections. Use for protecting data. Cannot be
modified after creation.
Dictionaries: Mutable, unordered key-value pairs. Fast lookup. Keys must be
unique and immutable.

7.2 When to Use Each Data Type


Definition
Use Strings: For text data, names, messages, immutable text storage.
Use Lists: For ordered collections that need to change, dynamic data storage,
when you need all modification operations.
Use Tuples: For fixed data that shouldn’t change, function return values, dictio-
nary keys, when immutability is important.
Use Dictionaries: For storing related information as key-value pairs, lookup
tables, configuration settings, mapping relationships.

8 Quick Reference Guide


8.1 String Operations
Operation Description
str[i] Access character at index i
str[i:j] Slice from index i to j-1
str[::step] Slice with step
str + str2 Concatenate strings
str * n Repeat string n times
len(str) Length of string
substring in str Check membership
[Link]() Convert to uppercase
[Link]() Convert to lowercase
[Link]() Remove leading/trailing spaces
[Link](old, Replace substring
new)
[Link]() Split into list
[Link](list) Join list into string

37
Unit-3: Complex Data Types BCS302: Python Programming

8.2 List Operations


Operation Description
list[i] Access element at index i
list[i:j] Slice from index i to j-1
[Link](x) Add element at end
[Link](i, x) Insert element at index i
[Link](x) Remove first occurrence of x
[Link]() Remove and return last element
[Link]() Sort in-place
[Link]() Reverse in-place
len(list) Number of elements
x in list Check membership
[Link](x) Count occurrences of x
[Link](x) Find index of first x

8.3 Dictionary Operations


Operation Description
dict[key] Access value by key
dict[key] = value Add/update key-value pair
[Link](key) Get value (returns None if missing)
[Link]() Get all keys
[Link]() Get all values
[Link]() Get key-value pairs
[Link](key) Remove and return value
[Link]() Remove all items
len(dict) Number of key-value pairs
key in dict Check if key exists

38

You might also like