Unit-3 Python Complex Data Types
Unit-3 Python Complex Data Types
str1=“Hello!”
str2=“world”
str3=str1+str2
print(“Concatenated string is :”, str3)
Output:
Concatenated string is : Hello! world
Output:
Enter your name: SHIV VEER
Hello! SHIV VEER . Welcome to python.
Python Programming Unit-3 Prof. SHIV VEER SINGH 9
Program to repeat a string using * operator [CO3]
str=“SHIV!” print(str * 3)
Output:
SHIV! SHIV! SHIV!
Output:
Name= Ojaswa Rajput and age = 14 Name = Adhya Rajput and age = 11
P Y T H O N
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
Fig: Indices in a string
Python Programming Unit-3 Prof. SHIV VEER SINGH 15
slicing [CO3]
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a
part of the string.
Example
Get the characters from position 2 to position 5 (not included):
S=“Python!”
print(S[1:4])
Output:
yth
Python Programming Unit-3 Prof. SHIV VEER SINGH 16
Program to demonstrate slicing operation [CO3]
str = “PYTHON”
print(“str [1:5] = ”, str[1:5])
print(“str [:6] = ”, str[:6]) #defaults to start of string
print(“str [1:] = ”, str[1:]) #defaults to end of string print(“str [:] = ”,
str[:]) #defaults to entire string
print(“str [1:20] =”, str[1:20]) #truncates to length of the string
Output:
str [1:5] = YTHO str [:6]
= PYTHON str [1:] =
YTHON str[ : ] =
PYTHON str [1:20] =
YTHON
\b Backspace
• Sequence types: strings, Unicode strings, lists, tuples, and range objects.
• String's literals are written in single or double quotes: 'xyzzy', "frobozz".
• Lists are constructed with square brackets, separating items with commas:
[a, b, c].
• Tuples are constructed by the comma operator (not within square brackets),
with or without enclosing parentheses, but an empty tuple must have the
enclosing parentheses, e.g., a, b, c or (). A single item tuple must have a trailing
comma, e.g., (d,).
• range objects are used to create a sequence of numeric values.
• We have used a comma “,” after the *num because the left hand side of the
assignment operation must be a tuple or list otherwise error will be encountered.
• In the left side, when we use * operator, we can also have other variables which can
be assigned the values. For example, we can pack two numbers into a variable and a
third number can be assigned to another variable as follows.
num1=1
num2=2
num3=3
*num,myNum=num1,num2,num3
#driver Code
my_list = [1, 2, 3, 4]
func(my_list) # This doesn't work
Python Programming Unit-3 Prof. SHIV VEER SINGH 37
Python program to understand need of unpacking [CO3]
Unpacking
We can use * to unpack the list so that all elements of it can
be passed as different parameters.
# A sample function that takes 4 arguments and prints them
def fun(a, b, c, d):
print(a, b, c, d)
# Driver Code Output
my_list = [1, 2, 3, 4] 1234
fun(*my_list) # Unpacking list into four arguments
Python Programming Unit-3 Prof. SHIV VEER SINGH 38
Mutable Sequences [CO3]
• Mutable Sequences:
Sequence that can change their state or contents are called mutable
sequence.
These are of type list, dict, set . Custom classes are generally
mutable.
List = [1, 2, 3, 4, 5, 6]
Output
# accessing a element
print(List[0]) 1
3
print(List[2]) Output
# Negative indexing
6
print(List[-1]) # print the last element of list 4
print(List[-3]) # print the third last element of list
Python Programming Unit-3 Prof. SHIV VEER SINGH 43
List methods [CO3]
Method Description Syntax Example output
# Using insert()
List.insert(3, 12) Output
List.insert(0, 'Begin')
print(List) ['Begin', 5, 6, 12]
# Creating a List
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# using Remove() method
List.remove(5)
List.remove(6)
Output
print(List) [1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
cubes = [ ]
for i in range (11):
cubes.append(i**3)
print(“cubes of numbers from 1-10: ”, cubes)
Output:
cubes of numbers from 1-10 :
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Python Programming Unit-3 Prof. SHIV VEER SINGH 51
Program to make a list of cubes using iterable [CO3]
Iterable:
An iterable is an object that can be used repeatedly in subsequent loop
statements, e.g. for loop
print([(x, y) for x in [10, 20, 30] for y in [30, 10, 40] if x!=y])
Output:
[(10, 30), (10, 40), (20, 30), (20, 10), (20, 40), (30, 10), (30, 40)]
list = [1, 2, 3, 4, 5]
length = len (list)
i=0
while i < length:
print(list[i]) Output
i += 1 1
2
3
4
5
Looping in lists
Method #4: Using list comprehension [CO3]
list = [1, 2, 3, 4, 5]
[print(i) for i in list]
Output
1
2
3
4
5
Looping in lists
Method #5: Using enumerate [CO3]
Tuple
• A tuple is a collection which is ordered and
unchangeable. In Python tuples are written with round
brackets.
• A tuple is an immutable sequence of Python objects.
Tup = (val1, val2, …….) where val can be integer, floating number, character or a string.
Example
tup = ("SHIV", "VEER", "SINGH")
print(tup)
Output:
("SHIV", "VEER", "SINGH")
Python Programming Unit-3 Prof. SHIV VEER SINGH 62
Access Tuple Items [CO3]
You can access tuple items by referring to the index number, inside square brackets:
Example
print the second item in the tuple:
tup1 = ("SHIV", "VEER", "SINGH")
tup2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) Output
print(tup1[0])
SHIV
print(tup2[3:6])
(4, 5, 6)
print(tup2[:4]) (1, 2, 3, 4)
print(tup2[4:]) (5, 6, 7, 8, 9, 10)
print(tup2[:]) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(tup2[-1]) // beginning from end 10
print(tup2[-3:-1]) (8, 9)
for x in thistuple:
print(x)
Output:
SHIV
VEER
SINGH
Python Programming Unit-3 Prof. SHIV VEER SINGH 65
Tuple Assignment [CO3]
It allows tuple of variables on left hand side of the assignment operator to be
assigned values from a tuple on the right hand side of the assignment operator.
Each value is assigned to its respective variable.
Example:
(a, b, c)= (1, 2, 3)
print (a, b, c) Output
Tup1=(100, 200, 300) 123
(a, b, c)= Tup1 100 200 300
print (a, b, c) 7 6.333333 3
(a, b, c) = (3 + 4, 7 / 3 + 4, 9 % 6)
print (a, b, c)
output:
Yes, 'SHIV' is in the thistuple
Python Programming Unit-3 Prof. SHIV VEER SINGH 67
Tuple Length [CO3]
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
thistuple = ("SHIV", "VEER", "SINGH")
print(len(thistuple))
3
Python Programming Unit-3 Prof. SHIV VEER SINGH 68
Tuple Methods [CO3]
Python has two built-in methods that you can use on tuples.
count(): returns the number of times a specified value occurs in a tuple
Tup=(1,2,3,3,5,6,3,8) Output
print(Tup.count(3)) 3
index(): Searches the tuple for a specified value and returns the position
of where it was found
Output
Tup=(1,2,3,4,5,6,7,8)
3
print(Tup.index(4))
Python Programming Unit-3 Prof. SHIV VEER SINGH 69
Join Two Tuples [CO3]
To join two or more tuples, you can use the + operator:
Example
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Output ('a', 'b', 'c', 1, 2, 3)
SETS
Change Items
Once a set is created, items of the set can’t be changed but
a new item can be added.
Note: If the item to remove does not exist, remove() will raise an error while
discard does not give error
Python Programming Unit-3 Prof. SHIV VEER SINGH 82
Join Two Sets [CO3]
• You can use the union() method that returns a new set containing all items
from both sets, or
• the update() method that inserts all the items from one set into
another:
Example
The union() method returns a new set with all items from both sets: set1 =
{"a", "b" , "c"}
set2 = {1, 2, 3} Output
set3 = set1.union(set2)
print(set3) {'c', 'b', 2, 3, 1, 'a'}
difference_update() Removes the items in this set that are also included in another,
specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other,
specified set(s)
isdisjoint() Returns whether two sets have an intersection or not
Dictionaries
Syntax:
dictionary_name = {key1:value1, key2:value2, key3:value3}
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
Output:
Mustang
Python Programming Unit-3 Prof. SHIV VEER SINGH 91
Accessing Items in Dictionaries [CO3]
There is also a method called get() that will give you the same result:
Example: Get the value of the "model" key:
thisdict ={"brand": "Ford", "model": "Mustang", "year": 1964 }
x = thisdict.get("model")
print(x)
Mustang
Method 2
The del keyword removes the item with the specified key name:
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
del thisdict["model"]
print(thisdict)
Output:
{'brand': 'Ford', 'year': 1964}
Python Programming Unit-3 Prof. SHIV VEER SINGH 98
Removing Items from Dictionaries [CO3]
Method 3
The del keyword can also delete the dictionary completely:
thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
del thisdict
print(thisdict)
Output:
#print statement will cause an error because "thisdict" no longer exists.