BCA SEM- 4 PYTHON WEBSOL UNIT - 2
Unit II
Data Structures and Sequences: Tuples, Lists and slicing, Built-in Sequence functions,
Dictionary, Sets; List, Set, and Dict Comprehensions. Functions: Namespaces, Scope, and
Local Functions; Returning Multiple Values.
Data Structures are a way of organizing data so that it can be accessed more efficiently
depending upon the situation. Data Structures are fundamentals of any programming
language around which a program is built. Python helps to learn the fundamental of these
data structures in a simpler way as compared to other programming languages.
Tuple :
A tuple in Python is an ordered collection of elements that is immutable, meaning its
contents cannot be changed after creation. Tuples are similar to lists in that they can store
items of different data types and are indexed by integers, but their immutability is the key
distinction. Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
Key characteristics of tuples:
Ordered:
The elements in a tuple maintain a specific order, and this order is preserved.
Immutable:
Once a tuple is created, its elements cannot be modified, added, or removed.
Heterogeneous:
Tuples can contain elements of different data types (e.g., integers, strings, floats, other lists
or tuples).
Allows duplicates:
Tuples can contain duplicate values.
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page 1
BCA SEM- 4 PYTHON WEBSOL UNIT - 2
name = ("raj", "karan", "sunil") name = ("raj", "karan", "sunil")
print(name) print(name[0])
('raj', 'karan', 'sunil') Raj
name = ("raj", "karan", "sunil") value= (10,20,30,40,50,60,70)
print(name[-1]) print(value)
sunil (10, 20, 30, 40, 50, 60, 70)
value= (10,20,30,40,50,60,70) value= (10,20,30,40,50,60,70)
print(value[3]) print(value[-2])
40 60
value= (10,20,30,40,50,60,70) value= (10,20,30,40,50,60,70)
print(value[1:]) print(value[1:5])
(20, 30, 40, 50, 60, 70) (20, 30, 40, 50)
value= (10,20,30,40,50,60,70) value= (10,20,30,40,50,60,70)
print(value[:5]) print(value[0:6:2])
(10, 20, 30, 40, 50) (10, 30, 50)
value= (10,20,10,40,10,60,20) value= (10,20,30,40,50,60,70)
a=[Link](10) a=[Link](40)
print(a) print(a)
3 3
List
A list in Python is used to store the sequence of various types of data. Python lists are
mutable type its mean we can modify its element after it created. However, Python consists
of six data-types that are capable to store the sequences, but the most common and reliable
type is the list.
A list can be defined as a collection of values or items of different types. The items in the list
are separated with the comma (,) and enclosed with the square brackets [].Lists are used to
store multiple items in a single variable.
A list in Python is a built-in, ordered, and mutable sequence data type used to store a
collection of items.
Key characteristics of Python lists:
Ordered: Elements maintain their insertion order, allowing access by index (starting from 0).
Mutable: Elements can be added, removed, or modified after the list is created.
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page 2
BCA SEM- 4 PYTHON WEBSOL UNIT - 2
Heterogeneous: Lists can contain items of different data types (e.g., integers, strings,
booleans, other lists).
Dynamic Sizing: Lists automatically adjust their size as elements are added or removed.
Common List Operations:
Adding Elements: append(), insert(), extend()
Removing Elements: remove(), pop(), clear()
Modifying Elements: Assigning new values to specific indices.
Slicing: Extracting sub-sequences of a list.
Iteration: Looping through list elements using for loops.
Characteristics of Lists
The list has the following characteristics:
The lists are ordered.
The element of the list can access by index.
The lists are the mutable type.
The lists are mutable types.
A list can store the number of various elements.
thislist = ["apple", "banana", "cherry"] ['apple', 'banana', 'cherry']
print(thislist)
List Items
List items are ordered, changeable, and allow duplicate [Link] items are indexed, the first
item has index [0], the second item has index [1] etc.
List Length
To determine how many items a list has, use the len() function:
thislist = ["apple", "banana", "cherry"] 3
print(len(thislist))
Access Items
List items are indexed and you can access them by referring to the index number:
thislist = ["apple", "banana", "cherry"] banana
print(thislist[1])
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page 3
BCA SEM- 4 PYTHON WEBSOL UNIT - 2
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
thislist = ["apple", "banana", "cherry"] cherry
print(thislist[-1])
Removing elements from the list
Python provides the remove() function which is used to remove the element from the list.
To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting or the remove() method
list1 = ['physics', 'chemistry', 1997, 2000]; ['physics', 'chemistry', 2000]
del list1[2];
print list1
# Creating a List [1, 3, 4, 5]
List = [1, 2, 3, 4, 5]
[Link](2)
print(List)
Cloning Lists
If we want to modify a list and also keep a copy of the original, we need to be able to make a
copy of the list itself, not just the reference. This process is sometimes called cloning, to
avoid the ambiguity of the word copy.
list1 = [10, 22, 44, 23, 4] [10, 22, 44, 23, 4]
list2 = list(list1) [10, 22, 44, 23, 4]
print(list1)
print(list2)
List operations
append() Method : The append() method appends an element to the end of the list.
name = ["Amit", "Jai", "Sonu"] ['Amit', 'Jai', 'Sonu', 'Mohit']
[Link]("Mohit")
print(name)
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page 4
BCA SEM- 4 PYTHON WEBSOL UNIT - 2
clear() Method : The clear() method removes all the elements from a list.
name = ["Amit", "Jai", "Sonu"] []
[Link]()
print(name)
Copy() :
The copy() method returns a copy of the specified list.
name = ["amit", "karan", "charu"] ['amit', 'karan', 'charu']
['amit', 'karan', 'charu']
x = [Link]()
print(x)
print(name)
count()
The count() method returns the number of elements with the specified value.
name = ["amit", "karan", "charu","amit"] 2
x = [Link]("amit")
print(x)
extend()
The extend() method adds the specified list elements (or any iterable) to the end of the current
list.
list1 = ["amit", "karan"] ['amit', 'karan', 'naman', 'raj']
list2 = ["naman","raj"]
[Link](list2)
print(list1)
sort()
the sort() method sorts the list ascending by [Link] can also make a function to decide
the sorting criteria(s).
name = ['raj', 'amit', 'jiya'] ['amit', 'jiya', 'raj']
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page 5
BCA SEM- 4 PYTHON WEBSOL UNIT - 2
[Link]()
print(name)
Set :
In Python, a set is a built-in data type used to store a collection of unique, unordered
elements. It is one of the four core collection types in Python, alongside lists, tuples, and
dictionaries.
Key characteristics of Python sets:
Uniqueness:
Sets do not allow duplicate elements. If an attempt is made to add a duplicate element, it
will be ignored, and the set will remain unchanged.
Unordered:
Elements within a set do not maintain any specific order. This means elements cannot be
accessed by an index or key, and their order may change upon different operations.
Mutable:
Sets are mutable, meaning elements can be added or removed after the set has been
created. However, the individual elements themselves must be immutable (e.g., numbers,
strings, tuples).
Mathematical Operations:
Sets support various mathematical set operations like union, intersection, difference, and
symmetric difference, making them useful for tasks involving comparisons and
relationships between collections of items.
Creating a Set:
Sets can be created using curly braces {} with elements separated by commas, or by using
the set() constructor.
thisset = {"apple", "banana", "cherry"} thisset = {"apple", "banana", "cherry"}
print(thisset)
print(len(thisset))
thisset = {"apple", "banana", "cherry"} thisset = {"apple", "banana", "cherry"}
for x in thisset: [Link]("orange")
print(x)
print(thisset)
thisset = {"apple", "banana", "cherry"} thisset = {"apple", "banana", "cherry"}
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page 6
BCA SEM- 4 PYTHON WEBSOL UNIT - 2
[Link]("banana") x = [Link]()
print(thisset) print(x)
print(thisset)
Dictionary:
In Python, a dictionary is a mutable, unordered collection of data values stored in key:value
pairs. It is a fundamental data structure used for storing and retrieving data efficiently based
on unique keys.
Key characteristics of Python dictionaries:
Key-value pairs:
Dictionaries store data as pairs, where each unique "key" maps to a specific "value."
Mutable:
Dictionaries can be modified after creation, allowing for the addition, deletion, or
modification of key-value pairs.
Ordered (from Python 3.7+):
While historically unordered, dictionaries in Python 3.7 and later versions maintain
insertion order.
Unique keys:
Each key within a dictionary must be unique. If you try to add a duplicate key, the existing
value associated with that key will be overwritten.
Immutable keys:
Keys must be of an immutable data type (e.g., strings, numbers, tuples). Mutable types like
lists or other dictionaries cannot be used as keys.
Values can be of any type:
Values can be of any valid Python data type, including lists, other dictionaries, or custom
objects.
Creating a dictionary:
Dictionaries are typically created using curly braces {} with key-value pairs separated by
colons : and individual pairs separated by commas ,.
thisdict = { car = {
"brand": "Ford", "brand": "Ford",
"model": "Mustang", "model": "Mustang",
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page 7
BCA SEM- 4 PYTHON WEBSOL UNIT - 2
"year": 1964 "year": 1964
} }
print(thisdict)
x = [Link]()
print(x)
car = { car = {
"brand": "Ford", "brand": "Ford",
"model": "Mustang", "model": "Mustang",
"year": 1964 "year": 1964
} }
x = [Link]() [Link]()
print(x) print(car)
Dict Comprehensions.
Dictionary comprehension in Python offers a concise way to create dictionaries from
iterables. It provides a more compact and often more readable alternative to
traditional for loops for constructing dictionaries.
Basic Syntax:
The fundamental structure of a dictionary comprehension is:
new_dict = {key_expression: value_expression for item in iterable}
key_expression: An expression that defines how the key for each item is derived.
value_expression: An expression that defines how the value for each item is derived.
item: The variable that takes on each element from the iterable during iteration.
iterable: Any object that can be iterated over (e.g., list, tuple, string, range, or another
dictionary's items()).
squares = {num: num**2 for num in range(1, 6)}
print(squares)
# Result: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Advantages:
Conciseness: Reduces multiple lines of code into a single, compact expression.
Readability: Can improve code clarity for simple transformations.
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page 8
BCA SEM- 4 PYTHON WEBSOL UNIT - 2
Efficiency: Often performs better than equivalent for loops, especially for larger datasets.
# Python code to demonstrate dictionary
# comprehension
# Lists to represent keys and values
keys = ['a','b','c','d','e']
values = [1,2,3,4,5] {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# but this line shows dict comprehension here
myDict = { k:v for (k,v) in zip(keys, values)}
# We can use below too
# myDict = dict(zip(keys, values))
print (myDict)
built-in functions:
Python provides several built-in functions that are particularly useful when working with
sequence types such as lists, tuples, strings, and ranges. These functions operate directly on
the sequence or its elements.
Here are some commonly used built-in functions for sequences:
len(sequence): Returns the number of items in a sequence.
my_list = [1, 2, 3, 4]
length = len(my_list) # length will be 4
min(sequence): Returns the smallest item in a non-empty sequence.
numbers = [5, 1, 9, 2]
minimum = min(numbers) # minimum will be 1
max(sequence): Returns the largest item in a non-empty sequence.
numbers = [5, 1, 9, 2]
maximum = max(numbers) # maximum will be 9
sum(iterable, start=0): Returns the sum of all items in an iterable (including sequences),
optionally starting with a given start value.
data = [10, 20, 30]
total = sum(data) # total will be 60
x = abs(-7.25) x = pow(4, 3)
Function :
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page 9
BCA SEM- 4 PYTHON WEBSOL UNIT - 2
functions are blocks of organized, reusable code that perform a specific task. They are
fundamental to structuring programs and promoting code reusability.
def keyword:
The def keyword stands for define. It is used to create a user-defined function. It marks
the beginning of a function block and allows you to group a set of statements so they can be
reused when the function is called.
Key aspects of Python functions:
Definition: Functions are defined using the def keyword, followed by the function name,
parentheses (), and a colon :. The code block within the function is indented.
Parameters and Arguments:
o Parameters: are placeholders defined in the function signature that receive input.
o Arguments: are the actual values passed to the function when it is called.
Return Values: Functions can return values using the return keyword. If no return statement
is explicitly used, the function implicitly returns None.
Types of Functions:
Built-in Functions: Provided by Python (e.g., print(), len(), type()).
User-defined Functions: Created by the programmer to perform specific tasks.
Third-party Functions: Available in external libraries or modules.
Benefits of using functions:
Modularity: Breaking down complex problems into smaller, manageable parts.
Reusability: Avoiding repetitive code by calling the same function multiple times.
Readability: Making code easier to understand and maintain.
Organization: Structuring code logically.
def show(): def add(a,b):
print("Hello from a function") return a+b
ans=add(20,40)
show() print(ans)
def evenOdd(x): def swap(x, y):
if (x % 2 == 0): temp = x
return "Even" x=y
else: y = temp
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page 10
BCA SEM- 4 PYTHON WEBSOL UNIT - 2
return "Odd"
x=2
print(evenOdd(16)) y=3
print(evenOdd(7)) swap(x, y)
print(x)
print(y)
def add(): def add(a,b):
a=10 c=a+b
b=20 print(c)
c=a+b add(40,50)
print(c)
add()
Namespaces:
a namespace is a mapping from names to objects. It functions like a dictionary, where keys
are identifiers (names of variables, functions, classes, etc.) and values are the corresponding
objects in memory. Namespaces provide a mechanism to prevent naming conflicts and
organize code by creating distinct contexts for identifiers.
Types of Namespaces:
Built-in Namespace:
This namespace contains all the built-in functions and exceptions provided by Python, such
as print(), len(), int(), NameError, etc. It is created when the Python interpreter starts and
remains active throughout the program's execution.
Global Namespace:
This namespace holds all the names defined at the top level of a module or script. It
becomes active when the module is loaded and persists until the program terminates.
Local Namespace:
This namespace is created when a function or method is called. It contains all the names
defined within that function or method's scope. This namespace is temporary and is
destroyed once the function completes its execution.
Importance of Namespaces:
Namespaces are fundamental to Python's object model and contribute to:
Avoiding Naming Collisions:
Different parts of a program can use the same name for different objects without
interference, as long as they reside in different namespaces.
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page 11
BCA SEM- 4 PYTHON WEBSOL UNIT - 2
Code Organization and Readability:
Namespaces help structure code by clearly defining the scope and availability of identifiers.
Encapsulation:
They support the concept of encapsulation by limiting the visibility of certain names to
specific contexts.
Global and Local Namespaces
Python has two types of namespaces: Global and Local. The Global namespace contains
names that are accessible throughout the entire program. On the other hand, Local
namespaces are specific to a particular function or block of code. Create Local
namespaces when a function is called and destroyed when it completes its execution.
# define global variable 10
global_var = 10 30
def my_function():
# define local variable
local_var = 20
# modify global variable value
global global_var
global_var = 30
# print global variable value
print(global_var)
# call the function and modify the global
variable
my_function()
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page 12
BCA SEM- 4 PYTHON WEBSOL UNIT - 2
# print the modified value of the global
variable
print(global_var)
30
print("Namespace Example")
#built-in namespace
a=10 #global namespace
def func1():
b=20 #local namespace
print(a+b)
func1()
return multiple values
a function can return multiple values by separating them with commas in
the return statement. When this is done, the values are implicitly packaged into a tuple and
returned as a single entity.
Methods for Returning Multiple Values:
Using Commas (Implicit Tuple).
This is the most common and straightforward method. The values are simply listed after
the return keyword, separated by commas.
def fun(): websol
return "websol", 20 20
s, x = fun()
print(s)
print(x)
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page 13