UNIT-3
PYTHON COMPLEX DATA TYPES
Using string data type and string operations:
Python, a string is a sequence of characters enclosed within either single quotes
(‘ ‘) or double quotes (" "). It is an immutable data type, which means once a
string is created, it cannot be modified.
Example-
my_string = "This is a my name."
print(my_string)
print(type(my_string))
Output-
This is a my name.
<class 'str'>
In this example, the variable my_string is assigned the value of the string "This
is a string." The print() function is then used to output the value of my_string to
the console. The type() function returns the type of the object that is passed to it
as an argument.
Properties of String Data Type in Python
Immutable: Strings in Python are immutable, which means that once a
string is created, it cannot be modified. Instead, any operation that appears
to modify a string actually creates a new string object.
Sequence: Strings in Python are sequences of characters, which means that
you can access individual characters in a string using indexing and slicing.
Unicode: Python 3. x uses Unicode to represent strings, which allows for
the representation of a wide range of characters from different languages
and scripts.
Concatenation: Strings in Python can be concatenated using the +
operator. For example, "Hello" + "World" would result in the string
"HelloWorld".
Methods: Python provides a range of built-in methods that can be used to
manipulate strings, such as the upper() and lower() methods to convert
strings to uppercase and lowercase, respectively.
Application of String Data Type in Python
Text Processing
User Input
Web Development
Data Analysis
Machine Learning
The below Python functions are used to change the case of the strings.
o lower(): Converts all uppercase characters in a string into lowercase
o upper(): Converts all lowercase characters in a string into uppercase
o title(): Convert string to title case
o swapcase(): Swap the cases of all characters in a string
o capitalize(): Convert the first character of a string to uppercase
Example-
text = 'itm College'
print("\nConverted String:")
print(text.upper())
print("\nConverted String:")
print(text.lower())
print("\nConverted String:")
print(text.title())
print("\nConverted String:")
print(text.swapcase())
print("\nConverted String:")
print(text.capitalize())
# original string never changes
print("\nOriginal String")
print(text)
Output-
Converted String:
ITM COLLEGE
Converted String:
itm college
Converted String:
Itm College
Converted String:
ITM cOLLEGE
Converted String:
Itm college
Original String
itm College
Here is the list of in-built Python string methods, that you can use to perform
actions on string:
Function Name Description
Converts the first character of the string to a capital
capitalize()
(uppercase) letter
Function Name Description
casefold() Implements caseless string matching
center() Pad the string with the specified character.
Returns the number of occurrences of a substring in the
count()
string.
encode() Encodes strings with the specified encoded scheme
endswith() Returns “True” if a string ends with the given suffix
Specifies the amount of space to be substituted with the
expandtabs()
“\t” symbol in the string
find() Returns the lowest index of the substring if it is found
format() Formats the string for printing it to console
format_map() Formats specified values in a string using a dictionary
Returns the position of the first occurrence of a substring
index()
in a string
Checks whether all the characters in a given string is
isalnum()
alphanumeric or not
isalpha() Returns “True” if all characters in the string are alphabets
Function Name Description
isdecimal() Returns true if all characters in a string are decimal
isdigit() Returns “True” if all characters in the string are digits
isidentifier() Check whether a string is a valid identifier or not
islower() Checks if all characters in the string are lowercase
Returns “True” if all characters in the string are numeric
isnumeric()
characters
Returns “True” if all characters in the string are printable
isprintable()
or the string is empty
Returns “True” if all characters in the string are
isspace()
whitespace characters
istitle() Returns “True” if the string is a title cased string
isupper() Checks if all characters in the string are uppercase
join() Returns a concatenated String
ljust() Left aligns the string according to the width specified
Converts all uppercase characters in a string into
lower()
lowercase
Function Name Description
lstrip() Returns the string with leading characters removed
maketrans() Returns a translation table
partition() Splits the string at the first occurrence of the separator
Replaces all occurrences of a substring with another
replace()
substring
rfind() Returns the highest index of the substring
Returns the highest index of the substring inside the
rindex()
string
rjust() Right aligns the string according to the width specified
rpartition() Split the given string into three parts
rsplit() Split the string from the right by the specified separator
rstrip() Removes trailing characters
splitlines() Split the lines at line boundaries
startswith() Returns “True” if a string starts with the given prefix
Function Name Description
Returns the string with both leading and trailing
strip()
characters
Converts all uppercase characters to lowercase and vice
swapcase()
versa
title() Convert string to title case
translate() Modify string according to given translation mappings
Converts all lowercase characters in a string into
upper()
uppercase
Returns a copy of the string with ‘0’ characters padded to
zfill()
the left side of the string
Defining List and List Slicing:
Lists are used to store multiple items in a single variable. Lists are one of 4 built-
in data types in Python used to store collections of data, the other 3 are Tuple, Set,
and Dictionary, all with different qualities and usage.
Lists are created using square brackets. List items are ordered, changeable, and
allow duplicate values. List items are indexed, the first item has index [0], the
second item has index [1] etc.
Example-
# Creating a List
List = []
print("Blank List: ")
print(List)
# Creating a List of numbers
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)
# Creating a List of strings and accessing using index
List = ["Geeks", "For", "Geeks"]
print("\nList Items: ")
print(List[0])
print(List[2])
Output-
Blank List:
[]
List of numbers:
[10, 20, 14]
List Items:
Geeks
Geeks
Python lets you use negative indexing as well. The negative indices are counted
from the right. The index -1 represents the final element on the List's right side,
followed by the index -2 for the next member on the left, and so on, until the last
element on the left is reached.
Example-
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
print("Accessing element using negative indexing")
# print the last element of list
print(List[-1])
# print the third last element of list
print(List[-3])
Output-
Accessing element using negative indexing
Geeks
For
Elements can be added to the List by using the built-in append () function. Only
one element at a time can be added to the list by using the append () method.
append() method only works for the addition of elements at the end of the List,
for the addition of elements at the desired position, insert() method is used.
Unlike append () which takes only one argument, the insert() method requires two
arguments(position, value).
Example-
List = []
print("Initial blank List: ")
print(List)
# Addition of Elements in the List
List.append(1)
List.append(2)
List.append(3)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)
List.insert(3, 12)
List.insert(0, 'Geeks')
print("\nList after performing Insert Operation: ")
print(List)
Output-
Initial blank List:
[]
List after Addition of Three elements:
[1, 2, 3, 4]
List after performing Insert Operation:
['Geeks', 1, 2, 3, 12, 4]
Elements can be removed from the List by using the built-in remove () function.
The remove () method removes the specified item. Remove method in List will
only remove the first occurrence of the searched element.
pop () function can also be used to remove and return an element from the list,
but by default it removes only the last element of the list, to remove an element
from a specific position of the List, the index of the element is passed as an
argument to the pop() method.
Slicing of a List
We can get substrings and sublists using a slice. In Python List, there are multiple
ways to print the whole list with all the elements, but to print a specific range of
elements from the list, we use the Slice operation. Slice operation is performed
on Lists with the use of a colon[:]. List slicing returns a new list from the existing
list.
Syntax is:
List_name[ Initial : End : IndexJump ]
Example-
# Creating a List
List = ['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
print("Initial List: ")
print(List)
# Print elements of a range using Slice operation
Sliced_List = List[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_List)
# Print elements from a pre-defined point to end
Sliced_List = List[5:]
print("\nElements sliced from 5th element till the end: ")
print(Sliced_List)
# Printing elements from beginning till end
Sliced_List = List[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_List)
Output-
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
Slicing elements in a range 3-8:
['K', 'S', 'F', 'O', 'R']
Elements sliced from 5th element till the end:
['F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
Printing all elements using slice operation:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
Use of Tuple data type:
Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-
in data types in Python used to store collections of data, the other 3 are List, Set,
and Dictionary, all with different qualities and usage. A tuple is a collection which
is ordered and unchangeable. Tuples are written with round brackets.
Tuple items are ordered, unchangeable, and allow duplicate values. Tuple items
are indexed, the first item has index [0], the second item has index [1] etc.
Example-
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
print(tuple1)
print(tuple2)
print(tuple3)
Output-
('apple', 'banana', 'cherry')
(1, 5, 7, 9, 3)
(True, False, False)
You may want to construct a list of objects that cannot be altered while the
application is running. Python Tuples are utilized to meet this requirement. They
are frequently utilized internally in many of the systems on which we rely, such
as databases.
Use of Dictionary data type:
A dictionary is a kind of data structure that stores items in key-value pairs. A key
is a unique identifier for an item, and a value is the data associated with that key.
Dictionaries often store information such as words and definitions, but they can
be used for much more.
Dictionaries are mutable in Python, which means they can be changed after they
are created. Dictionary keys are case sensitive, the same name but different cases
of Key will be treated distinctly.
As of Python version 3.7, dictionaries are ordered and can not contain duplicate
keys.
Example-
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
Dict[5] = {'Nested': {'1': 'Life', '2': 'Geeks'}}
print("\nAdding a Nested Key: ")
print(Dict)
Output-
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5:
{'Nested': {'1': 'Life', '2': 'Geeks'}}}
Here is a list of in-built dictionary functions with their description. You can use
these functions to operate on a dictionary.
Method Description
Remove all the elements from the
dict.clear()
dictionary
dict.copy() Returns a copy of the dictionary
dict.get(key, default = “None”) Returns the value of specified key
Returns a list containing a tuple for each
dict.items()
key value pair
dict.keys() Returns a list containing dictionary’s keys
Updates dictionary with specified key-
dict.update(dict2)
value pairs
Returns a list of all the values of
dict.values()
dictionary
pop() Remove the element with specified key
popItem() Removes the last inserted key-value pair
Method Description
dict.setdefault(key,default= set the key to the default value if the key is
“None”) not specified in the dictionary
returns true if the dictionary contains the
dict.has_key(key)
specified key.
Manipulations Building blocks of python programs:
In python variables, datatypes and functions are known as building blocks of
python programming language. We can manipulate them by using built-in
functions present in the library of python.
String manipulation methods:
Strings are fundamental and essential data structures that every Python
programmer works with. Now we will learn some cool operations to manipulate
the string. We will see how we can manipulate the string in a Pythonic way.
1. String Padding: Add Extra Character Elegantly
String padding is a term to adding characters to the beginning or end of a string
until it reaches a certain length. It can be useful in formatting text to align with
other data or to make it easier to read.
In Python, you can pad a string using the str.ljust(), str.rjust(), and str.center()
methods.
Example-
text = "Python"
padded_text = text.ljust(10)
print(padded_text)
padded_text = text.rjust(10, '-')
print(padded_text)
padded_text = text.center(10, '*')
print(padded_text)
Output-
Python
----Python
**Python**
2. String Splitting
String splitting refers to dividing a string into multiple substrings based on a
specified delimiter or separator. In Python, you can split a string using the
str.split() method.
Example-
text = "Hello world, how are you today?"
words = text.split()
print(words)
text = "apple,banana,orange,grape"
fruits = text.split(',')
print(fruits)
text = "apple-banana-orange-grape"
fruits = text.split('-', maxsplit=2)
print(fruits)
Output-
['Hello', 'world,', 'how', 'are', 'you', 'today?']
['apple', 'banana', 'orange', 'grape']
['apple', 'banana', 'orange-grape']
3. Use F-Strings for String Formatting
The f-strings are a feature in Python 3.6 and above that allow to embed
expressions inside string literals. They are a convenient way to create strings
containing dynamic values or format strings with variable values.
Example-
name = "Alice"
age = 30
greeting = f"Hello, my name is {name} and I'm {age} years old."
print(greeting)
price = 12.3456
formatted_price = f"The price is ${price:.2f}"
print(formatted_price)
Output-
Hello, my name is Alice and I'm 30 years old.
The price is $12.35
4. Eliminating Unnecessary Character of a String
Python's strip() method is useful for data cleaning, especially when removing
unnecessary characters from the beginning or end of strings. Data scientists often
find data cleaning tedious, but Python's built-in string manipulation methods
make it easier to remove unwanted characters from strings. The strip() method,
in particular, can remove leading or trailing characters from a string.
Example -
text = "!!!Hello, World!!!"
clean_text = text.strip("!")
print(clean_text)
Output:
Hello, World
5. Search for Substring Effective
Finding search string is a common requirement in daily programming. Python
comes with the two methods. One is find() method and another is index() method.
Example-
title = 'How to search substrings of Python Strings'
print(title.find('String'))
print(title.find('substring'))
print(title.find('Yang'))
title = 'How to search substrings of Python strings'
print(title.index('string'))
print(title.index('substring'))
print(title.index('Yang'))
Output-
35
14
-1
17
14
ERROR!
ValueError: substring not found
List manipulation methods:
Python lists can store an ordered collection of items, or elements, of varying
types. They are often used to compile multiple items into a single, mutable
variable, which is helpful for retrieving items, specifying outputs or performing
calculations quickly.
Let’s look at some different list methods in Python for Python lists:
S.no Method Description
1 append() Used for adding elements to the end of the List.
2 copy() It returns a shallow copy of a list
This method is used for removing all items from
3 clear()
the list.
4 count() These methods count the elements.
S.no Method Description
Adds each element of an iterable to the end of the
5 extend()
List
Returns the lowest index where the element
6 index()
appears.
7 insert() Inserts a given element at a given index in a list.
Removes and returns the last value from the List
8 pop()
or the given index value.
9 remove() Removes a given object from the List.
10 reverse() Reverses objects of the List in place.
Sort a List in ascending, descending, or user-
11 sort()
defined order
Calculates the minimum of all the elements of the
12 min()
List
Calculates the maximum of all the elements of
13 max()
the List.
Example-
List = ['Mathematics', 'chemistry', 1997, 2000]
List.append(20544)
print(List)
List.insert(2, 10087)
print(List)
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
# Add List2 to List1
List1.extend(List2)
print(List1)
# Add List1 to List2 now
List2.extend(List1)
print(List2)
List = [1, 2, 3, 4, 5]
print(sum(List))
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))
print(List.index(3))
numbers = [5, 2, 8, 1, 9]
print(min(numbers))
print(max(numbers))
List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
#Reverse flag is set True
List.sort(reverse=True)
print(List)
print(List.pop())
print(List.pop(0))
del List[0]
print(List)
List.remove(3)
print(List)
Output-
['Mathematics', 'chemistry', 1997, 2000, 20544]
['Mathematics', 'chemistry', 10087, 1997, 2000, 20544]
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
15
4
2
1
9
[5.33, 4.445, 3, 2.5, 2.3, 1.054]
1.054
5.33
[3, 2.5, 2.3]
[2.5, 2.3]
Dictionary manipulation methods:
Python Dictionary is like a map that is used to store data in the form of a key:
value pair. Python provides various built-in functions to deal with dictionaries.
Here’s a list of some important Python dictionary methods:
Functions Name Descriptions
clear() Removes all items from the dictionary
copy() Returns a shallow copy of the dictionary
fromkeys() Creates a dictionary from the given sequence
Functions Name Descriptions
get() Returns the value for the given key
items() Return the list with all dictionary keys with values
Returns a view object that displays a list of all the
keys() keys in the dictionary in order of insertion
pop() Returns and removes the element with the given key
Returns and removes the key-value pair from the
popitem() dictionary
Returns the value of a key if the key is in the
dictionary else inserts the key with a value to the
setdefault() dictionary
Returns a view object containing all dictionary
values, which can be accessed and iterated through
values() efficiently
Updates the dictionary with the elements from
another dictionary or an iterable of key-value pairs.
With this method, you can include new data or
update() merge it with existing dictionary entries
Example-
my_dict = {'1': 'Geeks', '2': 'For', '3': 'Geeks'}
my_dict.clear()
print(my_dict)
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(d.get('Name'))
print(d.get('Gender'))
print(list(d.items())[1][0])
print(list(d.items())[1][1])
print(list(d.keys()))
print(list(d.values()))
d.pop('Age')
print(d)
d1 = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
d2 = {'Name': 'Neha', 'Age': '22'}
d1.update(d2)
print(d1)
Output-
{}
Ram
None
Age
19
['Name', 'Age', 'Country']
['Ram', '19', 'India']
{'Name': 'Ram', 'Country': 'India'}
{'Name': 'Neha', 'Age': '22', 'Country': 'India'}
Python Functions:
Python Functions is a block of statements that return the specific task. The idea
is to put some commonly or repeatedly done tasks together and make a function
so that instead of writing the same code again and again for different inputs, we
can do the function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions-
Increase Code Readability
Increase Code Reusability
Types of Functions in Python:
Below are the different types of functions in Python:
Built-in library function: These are Standard functions in Python that are
available to use.
User-defined function: We can create our own functions based on our
requirements.
Python's standard library includes number of built-in functions. Some of Python's
built-in functions are print(), int(), len(), sum(), etc. In addition to the built-in
functions ,we can also create our own functions. These functions are called user-
defined functions.
Syntax-
Creating a Function in Python-
We can define a function in Python, using the def keyword. We can add any type
of functionalities and properties to it as we require. By the following example,
we can understand how to write a function in Python.
Example-
# A simple Python function
def fun():
print("Welcome to GFG")
Calling a Function in Python-
After creating a function in Python we can call it by using the name of the
functions Python followed by parenthesis containing parameters of that particular
function. Below is the example for calling def function Python.
Example-
# A simple Python function
def fun():
print("Welcome to GFG")
# Driver code to call a function
fun()
Output-
Welcome to GFG
Arguments are the values passed inside the parenthesis of the function. A
function can have any number of arguments separated by a comma.
The function return statement is used to exit from a function and go back
to the function caller and return the specified value or data item to the
caller.
Example with argument-
def greet(name):
print("Hello", name)
def add(num1: int, num2: int):
num3 = num1 + num2
return num3
# Driver code
greet("John")
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Output-
Hello John
The addition of 5 and 15 results 20.
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments
Organizing python codes using functions:
# A simple Python function to check whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)
Output-
Even
Odd