Unit i Introduction to Python
Unit i Introduction to Python
Python installation, Python syntax, Scripts, Native Data Types, Booleans, Numbers, Lists, Tuple,
Sets, Dictionaries, Comprehensions, List Comprehensions, Dictionary Comprehensions, Set
Comprehensions
Python - Syntax
The Python syntax defines a set of rules that are used to create a
Python Program. The Python Programming Language Syntax has
many similarities to Perl, C, and Java Programming Languages.
However, there are some definite differences between the
languages.
$ python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
Here >>> denotes a Python Command Prompt where you can type
your commands. Let's type the following text at the Python prompt
and press the Enter −
If you are running older version of Python, like Python 2.4.x, then
you would need to use print statement without parenthesis as
in print "Hello, World!". However in Python version 3.x, this
produces the following result −
Hello, World!
$ python3 test.py
Hello, World!
#!/usr/bin/python3
Hello, World!
Python Identifiers
A Python identifier is a name used to identify
a variable, function, class, module or other object. An identifier
starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores and digits (0 to 9).
And as assert
In is lambda
Or pass raise
if True:
print ("True")
else:
print ("False")
if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False")
Thus, in Python all the continuous lines indented with same number
of spaces would form a block. The following example has various
statement blocks −
Do not try to understand the logic at this point of time. Just make
sure you understood various blocks even if they are without braces.
import sys
try:
# open file stream
file = open(file_name, "w")
except IOError:
print "There was an error writing to", file_name
sys.exit()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
file_text = raw_input("Enter text: ")
if file_text == file_finish:
# close the file
file.close
break
file.write(file_text)
file.write("\n")
file.close()
file_name = raw_input("Enter filename: ")
if len(file_name) == 0:
print "Next time please enter something"
sys.exit()
try:
file = open(file_name, "r")
except IOError:
print "There was an error reading file"
sys.exit()
file_text = file.read()
file.close()
print file_text
total = item_one + \
item_two + \
item_three
Quotations in Python
Python accepts single ('), double (") and triple (''' or """) quotes to
denote string literals, as long as the same type of quote starts and
ends the string.
The triple quotes are used to span the string across multiple lines.
For example, all the following are legal −
word = 'word'
print (word)
Comments in Python
A comment is a programmer-readable explanation or annotation in
the Python source code. They are added with the purpose of making
the source code easier for humans to understand, and are ignored
by Python interpreter
A hash sign (#) that is not inside a string literal begins a comment.
All characters after the # and up to the end of the physical line are
part of the comment and the Python interpreter ignores them.
# First comment
print ("Hello, World!") # Second comment
Hello, World!
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
'''
This is a multiline
comment.
'''
#!/usr/bin/python
Here, "\n\n" is used to create two new lines before displaying the
actual line. Once the user presses the key, the program ends. This is
a nice trick to keep a console window open until the user is done
with an application.
Header lines begin the statement (with the keyword) and terminate
with a colon ( : ) and are followed by one or more lines which make
up the suite. For example −
if expression :
suite
elif expression :
suite
else :
suite
$ python3 -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
[ etc. ]
You can also program your script in such a way that it should accept
various options. Command Line Arguments is an advanced topic and
should be studied a bit later once you have gone through rest of the
Python concepts.
Scripts
A Python script or program is a file containing executable Python code. Being able
to run Python scripts and code is probably the most important skill that you need as
a Python developer. By running your code, you'll know if it works as planned. You'll
also be able to test and debug the code to fix errors and issues
Native Data Types
Lists
Python Lists are just like dynamically sized arrays, declared in other
languages (vector in C++ and ArrayList in Java). In simple language, a
list is a collection of things, enclosed in [ ] and separated by commas.
The list is a sequence data type which is used to store the collection
of data. Tuples and String are other types of sequence data types.
print(Var)
Output:
["Geeks", "for", "Geeks"]
Lists are the simplest containers that are an integral part of the
Python language. Lists need not be homogeneous always which
makes it the most powerful tool in Python. A single list may contain
DataTypes like Integers, Strings, as well as Objects. Lists are mutable,
and hence, they can be altered even after their creation.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the
square brackets[]. Unlike Sets, a list doesn’t need a built-in function
for its creation of a list.
Note: Unlike Sets, the list may contain mutable elements.
Python3
# Creation of List
# Creating a List
List = []
print(List)
print(List)
# using index
print(List[0])
print(List[2])
Output
Blank List:
[]
List of numbers:
[10, 20, 14]
List Items:
Geeks
Geeks
Complexities for Creating Lists
Time Complexity: O(1)
Space Complexity: O(n)
Accessing elements from the List
In order to access the list items refer to the index number. Use the
index operator [ ] to access an item in a list. The index must be an
integer. Nested lists are accessed using nested indexing.
Example 1: Accessing elements from list
Python3
# Python program to demonstrate
print(List[0])
print(List[2])
Output
Accessing a element from the list
Geeks
Geeks
# Creating a List
List1 = []
print(len(List1))
print(len(List2))
Output
0
3
Example 1:
Python3
lst = string.split()
Output:
Enter elements: GEEKS FOR GEEKS
The list is: ['GEEKS', 'FOR', 'GEEKS']
Example 2:
Python
elements:").strip().split()))[:n]
Output:
Enter the size of list : 4
Enter the integer elements: 6 3 9 10
The list is: [6, 3, 9, 10]
To know more see this.
Adding Elements to a Python List
Method 1: Using append() method
# Creating a List
List = []
print(List)
# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print(List)
# using Iterator
List.append(i)
print(List)
List.append((5, 6))
print(List)
# Addition of List to a List
List.append(List2)
print(List)
Output
Initial blank List:
[]
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).
Python3
# Creating a List
List = [1,2,3,4]
print(List)
# Addition of Element at
# specific Position
List.insert(3, 12)
List.insert(0, 'Geeks')
print(List)
Output
Initial List:
[1, 2, 3, 4]
# Creating a List
List = [1, 2, 3, 4]
print(List)
print(List)
Output
Initial List:
[1, 2, 3, 4]
# Creating a List
List = [1, 2, 3, 4, 5, 6,
print(List)
List.remove(5)
List.remove(6)
print(List)
Output
Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# Creating a List
List = [1, 2, 3, 4, 5, 6,
List.remove(i)
print(List)
Output
List after Removing a range of elements:
[5, 6, 7, 8, 9, 10, 11, 12]
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(:)
To print elements from beginning to a range use:
[: Index]
To print elements from end-use:
[:-Index]
To print elements from a specific Index till the end use
[Index:]
To print the whole list in reverse order, use
[::-1]
Note – To print elements of List from rear-end, use Negative Indexes.
print(List)
Sliced_List = List[3:8]
print(Sliced_List)
Sliced_List = List[5:]
print(Sliced_List)
Sliced_List = List[:]
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']
List Comprehension
Python List comprehensions are used for creating new lists from
other iterables like tuples, strings, arrays, lists, etc. A list
comprehension consists of brackets containing the expression, which
is executed for each element along with the for loop to iterate over
each element.
Syntax:
newList = [ expression(element) for element in oldList if condition ]
Example:
Python3
# comprehension in Python
print(odd_square)
Output
[1, 9, 25, 49, 81]
For better understanding, the above code is similar to as follows:
Python3
odd_square = []
if x % 2 == 1:
odd_square.append(x**2)
print(odd_square)
Output
[1, 9, 25, 49, 81]
Refer to the below articles to get detailed information about List
Comprehension.
List Methods
Function Description
Removes and returns the item at the specified index. If no index is provided,
pop()
it removes and returns the last item.
Function Description
cmp() This function returns 1 if the first list is “greater” than the second list
return true if any element of the list is true. if the list is empty, return
any()
false
accumulate( apply a particular function passed in its argument to all of the list
) elements returns a list containing the intermediate results
map() returns a list of the results after applying the given function to each item
Function Description
of a given iterable
This function can have any number of arguments but only one
lambda()
expression, which is evaluated and returned.
Tuple
Python Tuples
Tuple is a collection of Python objects much like a list. The sequence
of values stored in a tuple can be of any type, and they are indexed by
integers.
Values of a tuple are syntactically separated by ‘commas’. Although it
is not necessary, it is more common to define a tuple by closing the
sequence of values in parentheses. This helps in understanding the
Python tuples more easily.
Creating a Tuple
In Python, tuples are created by placing a sequence of values
separated by ‘comma’ with or without the use of parentheses for
grouping the data sequence.
Note: Creation of Python tuple without the use of parentheses is
known as Tuple Packing.
Python program to demonstrate the addition of elements in a Tuple.
Python3
Tuple1 = ()
# Creating a Tuple
print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print(tuple(list1))
# Creating a Tuple
Tuple1 = tuple('Geeks')
print(Tuple1)
Output:
Initial empty Tuple:
()
# Creating a Tuple
print(Tuple1)
# Creating a Tuple
Tuple1 = (0, 1, 2, 3)
print(Tuple3)
# Creating a Tuple
# with repetition
Tuple1 = ('Geeks',) * 3
print(Tuple1)
# Creating a Tuple
Tuple1 = ('Geeks')
n = 5
for i in range(int(n)):
Tuple1 = (Tuple1,)
print(Tuple1)
Output:
Tuple with Mixed Datatypes:
(5, 'Welcome', 7, 'Geeks')
# Accessing Tuple
# with Indexing
Tuple1 = tuple("Geeks")
print(Tuple1[0])
# Tuple unpacking
# values of Tuple1
a, b, c = Tuple1
print(a)
print(b)
print(c)
Output:
First element of Tuple:
G
Values after unpacking:
Geeks
For
Geeks
Concatenation of Tuples
Concatenation of tuple is the process of joining two or more Tuples.
Concatenation is done by the use of ‘+’ operator. Concatenation of
tuples is done always from the end of the original tuple. Other
arithmetic operations do not apply on Tuples.
Note- Only the same datatypes can be combined with concatenation,
an error arises if a list and a tuple are combined.
Python3
# Concatenation of tuples
Tuple1 = (0, 1, 2, 3)
print("Tuple 1: ")
print(Tuple1)
print("\nTuple2: ")
print(Tuple2)
print(Tuple3)
Output:
Tuple 1:
(0, 1, 2, 3)
Tuple2:
('Geeks', 'For', 'Geeks')
Slicing of Tuple
Slicing of a Tuple is done to fetch a specific range or slice of sub-
elements from a Tuple. Slicing can also be done to lists and arrays.
Indexing in a list results to fetching a single element whereas Slicing
allows to fetch a set of elements.
Note- Negative Increment values can also be used to reverse the
sequence of Tuples.
Python3
# Slicing of a Tuple
# Slicing of a Tuple
# with Numbers
Tuple1 = tuple('GEEKSFORGEEKS')
print(Tuple1[1:])
print(Tuple1[::-1])
Output:
Removal of First Element:
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')
# Deleting a Tuple
Tuple1 = (0, 1, 2, 3, 4)
del Tuple1
print(Tuple1)
Built-in-
Method Description
Find in the tuple and returns the index of the given value where it’s
index( )
available
Built-In Functions
Built-in
Function Description
return true if any element of the tuple is true. if tuple is empty, return
any() false
sorted() input elements in the tuple and return a new sorted list
Tuples VS Lists:
Similarities Differences
Methods that can be used we generally use ‘tuples’ for heterogeneous (different)
for both lists and tuples: data types and ‘lists’ for homogeneous (similar) data
count(), Index() types.
Tuples can be stored in lists. Iterating through a ‘tuple’ is faster than in a ‘list’.
Lists can be stored in tuples. ‘Lists’ are mutable whereas ‘tuples’ are immutable.
Both ‘tuples’ and ‘lists’ can Tuples that contain immutable elements can be used as a
be nested. key for a dictionary.
Sets
Python Sets
In Python, a Set is an unordered collection of data types that is
iterable, mutable and has no duplicate elements. The order of
elements in a set is undefined though it may consist of various
elements. The major advantage of using a set, as opposed to a list, is
that it has a highly optimized method for checking whether a specific
element is contained in the set.
Python3
my_set = {1, 2, 3}
print(my_set)
Output
{1, 2, 3}
Accessing a Set
# Creating a set
print("\nInitial set")
print(set1)
# for loop
for i in set1:
# using in keyword
print("\n")
print("Geeks" in set1)
Output
Initial set
{'Geeks.', 'For', 'Geeks'}
Elements of set:
Geeks. For Geeks
True
Using pop() method:
Pop() function can also be used to remove and return an element from
the set, but it removes only the last element of the set.
Note: If the set is unordered then there’s no such way to determine
which element is popped by using the pop() function.
Python3
# Creating a Set
set1 = set([1, 2, 3, 4, 5, 6,
print(set1)
set1.pop()
print(set1)
Output
Initial Set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Python3
def create_set():
my_set = {1, 2, 3, 4, 5}
print(my_set)
def add_element():
my_set = {1, 2, 3, 4, 5}
my_set.add(6)
print(my_set)
def remove_element():
my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set)
def clear_set():
my_set = {1, 2, 3, 4, 5}
my_set.clear()
print(my_set)
def set_union():
set1 = {1, 2, 3}
set2 = {4, 5, 6}
my_set = set1.union(set2)
print(my_set)
def set_intersection():
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
my_set = set1.intersection(set2)
print(my_set)
def set_difference():
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
my_set = set1.difference(set2)
print(my_set)
def set_symmetric_difference():
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
my_set = set1.symmetric_difference(set2)
print(my_set)
def set_subset():
set1 = {1, 2, 3, 4, 5}
set2 = {2, 3, 4}
subset = set2.issubset(set1)
print(subset)
def set_superset():
set1 = {1, 2, 3, 4, 5}
set2 = {2, 3, 4}
superset = set1.issuperset(set2)
print(superset)
if __name__ == '__main__':
create_set()
add_element()
remove_element()
clear_set()
set_union()
set_intersection()
set_difference()
set_symmetric_difference()
set_subset()
set_superset()
Output
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6}
{1, 2, 4, 5}
set()
{1, 2, 3, 4, 5, 6}
{4, 5}
{1, 2, 3}
{1, 2, 3, 6, 7, 8}
True
True
Advantages:
Unique Elements: Sets can only contain unique elements, so
they can be useful for removing duplicates from a collection of
data.
Fast Membership Testing: Sets are optimized for fast
membership testing, so they can be useful for determining
whether a value is in a collection or not.
Mathematical Set Operations: Sets support mathematical
set operations like union, intersection, and difference, which
can be useful for working with sets of data.
Mutable: Sets are mutable, which means that you can add or
remove elements from a set after it has been created.
Disadvantages:
Set Methods
Function Description
another
Dictionaries
What is a Python Dictionary?
Dictionaries in Python is a data structure, used to store values in
key:value format. This makes it different from lists, tuples, and arrays
as in a dictionary each key has an associated value.
Note: As of Python version 3.7, dictionaries are ordered and can not
contain duplicate keys.
How to Create a Dictionary
In Python, a dictionary can be created by placing a sequence of
elements within curly {} braces, separated by a ‘comma’.
The dictionary holds pairs of values, one being the Key and the other
corresponding pair element being its Key:value.
Values in a dictionary can be of any data type and can be duplicated,
whereas keys can’t be repeated and must be immutable.
Note – Dictionary keys are case sensitive, the same name but
different cases of Key will be treated distinctly.
Output
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{'Name': 'Geeks', 1: [1, 2, 3, 4]}
Dictionary Methods
Here is a list of in-built dictionary functions with their description. You
can use these functions to operate on a dictionary.
Method Description
Output:
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4,
'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala']
Comprehensions
Comprehensions in Python provide us with a short and concise way to
construct new sequences (such as lists, sets, dictionaries, etc.) using
previously defined sequences. Python supports the following 4 types
of comprehension:
List Comprehensions
Dictionary Comprehensions
Set Comprehensions
Generator Comprehensions
List Comprehensions
List Comprehensions provide an elegant way to create new lists. The
following is the basic structure of list comprehension:
Syntax: output_list = [output_exp for var in input_list if
(var satisfies this condition)]
Note that list comprehension may or may not contain an if condition.
List comprehensions can contain multiple
Example 1: Generating an Even list WITHOUT using List
comprehensions
0 seconds of 0 secondsVolume 0%
Suppose we want to create an output list that contains only the even
numbers which are present in the input list. Let’s see how to do this
using loops, list comprehension, and list comprehension, and decide
which method suits you better.
Python3
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
output_list = []
Output:
Output List using for loop: [2, 4, 4, 6]
Example 2: Generating Even list using List comprehensions
Here we use the list comprehensions in Python. It creates a new list
named list_using_comp by iterating through each element var in
the input_list. Elements are included in the new list only if they
satisfy the condition, which checks if the element is even. As a result,
the output list will contain all even numbers.
Python3
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
input_list = [1, 2, 3, 4, 5, 6, 7]
output_dict = {}
Output:
Output Dictionary using for loop: {1: 1, 3: 27, 5: 125, 7: 343}
Example 2: Generating odd number with their cube
values with using dictionary comprehension
We are using dictionary comprehension in Python. It initializes
an list containing numbers from 1 to 7. It then constructs a new
dictionary using dictionary comprehension. For each odd
number var in the list, it calculates the cube of the number and
assigns the result as the value to the key var in the dictionary.
Python3
input_list = [1,2,3,4,5,6,7]
Output:
Output Dictionary using dictionary comprehensions: {1: 1, 3:
27, 5: 125, 7: 343}
Set Comprehensions
Set comprehensions are pretty similar to list comprehensions. The
only difference between them is that set comprehensions use curly
brackets { }
Let’s look at the following example to understand set
comprehensions.
Example 1 : Checking Even number Without using set
comprehension
Suppose we want to create an output set which contains only the
even numbers that are present in the input list. Note that set will
discard all the duplicate values. Let’s see how we can do this using for
loops and set comprehension.
Python3
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
output_set = set()
Output:
Output Set using for loop: {2, 4, 6}
Example 2: Checking Even number using set comprehension
We will use set comprehension to initializes a list with integer values.
The code then creates a new set using set comprehension. It iterates
through the elements of the input_list, and for each element, it
checks whether it’s even. If the condition is met, the element is added
to the set. The printed output which will contain unique even numbers
from the list.
Python3
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
Output:
Output Set using set comprehensions: {2, 4, 6}
Set Comprehension
Set is used to display the unique elements from a given collection. Let's
obtain the square of all elements of list using set.
Example - 1
1. list1=[2,3,4,5,6,7,8,9,10]
2. result_set=set()
3. for i in list1:
4. result_set.add(i**2)
5. print("The square of the numbers present in list1 is: ",result_set)
Output-
The square of the numbers present in list1 is: {64, 4, 36, 100, 9, 16, 49,
81, 25}
In the program given below, we have done the same thing using
comprehension.
1. list1=[2,3,4,5,6,7,8,9,10]
2. result_set={i**2 for i in list1}
3. print("The square of the numbers obtained through set comprehension
: ",result_set)
Output-
The square of the numbers obtained through set comprehension: {64, 4, 36,
100, 9, 16, 49, 81, 25}
We have taken each element from list1 and provided the expression in
result_set for calculating the square of these elements.
UNIT II
Strings and modules: String operation, Formatting, Bytes, Encoding, Regular Expressions,
Verbose, module declaration, Importing modules, Objects, and Indenting as Requirement,
Exceptions, Unbound Variables, Lambda Functions and map
Python String
A String is a data structure in Python that represents a sequence of
characters. It is an immutable data type, meaning that once you have
created a string, you cannot change it. Strings are used widely in many
different applications, such as storing and manipulating text data,
representing names, addresses, and other types of data that can be
represented as text.
What is a String in Python?
Python does not have a character data type, a single character is
simply a string with a length of 1.
Example:
"Geeksforgeeks" or 'Geeksforgeeks' or "a"
Python3
print('A')
Output:
A Computer Science portal for geeks
A
Creating a String in Python
Strings in Python can be created using single quotes or double
quotes or even triple quotes. Let us see how we can define a string in
Python.
Example:
In this example, we will demonstrate different ways to create a Python
String. We will create a string using single quotes (‘ ‘), double quotes (”
“), and triple double quotes (“”” “””). The triple quotes can be used to
declare multiline strings in Python.
Python3
# Creation of String
# Creating a String
print(String1)
# Creating a String
print(String1)
# Creating a String
print(String1)
For
Life'''
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
Creating a multiline String:
Geeks
For
Life
Accessing characters in Python String
In Python, individual characters of a String can be accessed by using
the method of Indexing. Indexing allows negative address references
to access characters from the back of the String, e.g. -1 refers to the
last character, -2 refers to the second last character, and so on.
While accessing an index out of the range will cause an IndexError.
Only Integers are allowed to be passed as an index, float or other types
that will cause a TypeError.
Example:
In this example, we will define a string in Python and access its
characters using positive and negative indexing. The 0th element will
be the first character of the string whereas the -1th element is the last
character of the string.
Python3
# characters of String
String1 = "GeeksForGeeks"
print(String1)
print(String1[0])
print(String1[-1])
Output:
Initial String:
GeeksForGeeks
First character of String is:
G
Last cha racter of String is:
s
String Slicing
In Python, the String Slicing method is used to access a range of
characters in the String. Slicing in a String is done by using a Slicing
operator, i.e., a colon (:). One thing to keep in mind while using this
method is that the string returned after slicing includes the character
at the start index but not the character at the last index.
Example:
In this example, we will use the string-slicing method to extract a
substring of the original string. The [3:12] indicates that the string
slicing will start from the 3rd index of the string to the 12th index,
(12th character not including). We can also use negative indexing in
string slicing.
Python3
# Python Program to
# Creating a String
String1 = "GeeksForGeeks"
print(String1)
print(String1[3:12])
print(String1[3:-2])
Output:
Initial String:
GeeksForGeeks
Slicing characters from 3-12:
ksForGeek
Slicing characters between 3rd and 2nd last character:
ksForGee
Reversing a Python String
By accessing characters from a string, we can also reverse strings in
Python. We can Reverse a string by using String slicing method.
Example:
In this example, we will reverse a string by accessing the index. We did
not specify the first two parts of the slice indicating that we are
considering the whole string, from the start index to the last index.
Python3
gfg = "geeksforgeeks"
print(gfg[::-1])
Output:
skeegrofskeeg
Example:
We can also reverse a string by using built-
in join and reversed functions, and passing the string as the parameter
to the reversed() function.
Python3
gfg = "geeksforgeeks"
gfg = "".join(reversed(gfg))
print(gfg)
Output:
skeegrofskeeg
Deleting/Updating from a String
In Python, the Updation or deletion of characters from a String is not
allowed. This will cause an error because item assignment or item
deletion from a String is not supported. Although deletion of the entire
String is possible with the use of a built-in del keyword. This is because
Strings are immutable, hence elements of a String cannot be changed
once assigned. Only new strings can be reassigned to the same name.
Updating a character
A character of a string can be updated in Python by first converting the
string into a Python List and then updating the element in the list. As
lists are mutable in nature, we can update the character and then
convert the list back into the String.
Another method is using the string slicing method. Slice the string
before the character you want to update, then add the new character
and finally add the other part of the string again by string slicing.
Example:
In this example, we are using both the list and the string slicing
method to update a character. We converted the String1 to a list,
changes its value at a particular element, and then converted it back
to a string using the Python string join() method.
In the string-slicing method, we sliced the string up to the character we
want to update, concatenated the new character, and finally
concatenate the remaining part of the string.
Python3
# character of a String
print(String1)
## As python strings are immutable, they don't support item updation directly
list1 = list(String1)
list1[2] = 'p'
String2 = ''.join(list1)
print(String2)
#2
print(String3)
Output:
Initial String:
Hello, I'm a Geek
Updating character at 2nd Index:
Heplo, I'm a Geek
Heplo, I'm a Geek
Updating Entire String
As Python strings are immutable in nature, we cannot update the
existing string. We can only assign a completely new value to the
variable with the same name.
Example:
In this example, we first assign a value to ‘String1’ and then updated it
by assigning a completely different value to it. We simply changed its
reference.
Python3
# entire String
# Updating a String
print(String1)
Output:
Initial String:
Hello, I'm a Geek
Updated String:
Welcome to the Geek World
Deleting a character
Python strings are immutable, that means we cannot delete a
character from it. When we try to delete thecharacter using
the del keyword, it will generate an error.
Python3
# character of a String
print(String1)
del String1[2]
print(String1)
Output:
Initial String:
Hello, I'm a Geek
Deleting character at 2nd Index:
Traceback (most recent call last):
File "e:\GFG\Python codes\Codes\demo.py", line 9, in <module>
del String1[2]
TypeError: 'str' object doesn't support item deletion
But using slicing we can remove the character from the original string
and store the result in a new string.
Example:
In this example, we will first slice the string up to the character that we
want to delete and then concatenate the remaining string next from
the deleted character.
Python3
print(String1)
# Deleting a character
# of the String
print(String2)
Output:
Initial String:
Hello, I'm a Geek
Deleting character at 2nd Index:
Helo, I'm a Geek
Deleting Entire String
Deletion of the entire string is possible with the use of del keyword.
Further, if we try to print the string, this will produce an error because
the String is deleted and is unavailable to be printed.
Python3
# Python Program to Delete
# entire String
print(String1)
# Deleting a String
del String1
print(String1)
Error:
Traceback (most recent call last):
File "/home/e4b8f2170f140da99d2fe57d9d8c6a94.py", line 12, in
print(String1)
NameError: name 'String1' is not defined
Escape Sequencing in Python
While printing Strings with single and double quotes in it
causes SyntaxError because String already contains Single and
Double Quotes and hence cannot be printed with the use of either of
these. Hence, to print such a String either Triple Quotes are used or
Escape sequences are used to print Strings.
Escape sequences start with a backslash and can be interpreted
differently. If single quotes are used to represent a string, then all the
single quotes present in the string must be escaped and the same is
done for Double Quotes.
Example:
Python3
# of String
# Initial String
print(String1)
print(String1)
print(String1)
String1 = "C:\\Python\\Geeks\\"
print(String1)
# use of Tab
String1 = "Hi\tGeeks"
print("\nTab: ")
print(String1)
String1 = "Python\nGeeks"
print(String1)
Output:
Initial String with use of Triple Quotes:
I'm a "Geek"
Escaping Single Quote:
I'm a "Geek"
Escaping Double Quotes:
I'm a "Geek"
Escaping Backslashes:
C:\Python\Geeks\
Tab:
Hi Geeks
New Line:
Python
Geeks
Example:
To ignore the escape sequences in a String, r or R is used, this implies
that the string is a raw string and escape sequences inside it are to be
ignored.
Python3
String1 = "\110\145\154\154\157"
print(String1)
# Using raw String to
print(String1)
print(String1)
print(String1)
Output:
Printing in Octal with the use of Escape Sequences:
Hello
Printing Raw String in Octal Format:
This is \110\145\154\154\157
Printing in HEX with the use of Escape Sequences:
This is Geeks in HEX
Printing Raw String in HEX Format:
This is \x47\x65\x65\x6b\x73 in \x48\x45\x58
Formatting of Strings
Strings in Python can be formatted with the use of format() method
which is a very versatile and powerful tool for formatting Strings.
Format method in String contains curly braces {} as placeholders
which can hold arguments according to position or keyword to specify
the order.
Example 1:
In this example, we will declare a string which contains the curly
braces {} that acts as a placeholders and provide them values to see
how string declaration position matters.
Python3
# Formatting of Strings
# Default order
print(String1)
# Positional Formatting
print(String1)
# Keyword Formatting
print(String1)
Output:
Print String in default order:
Geeks For Life
Print String in Positional order:
For Geeks Life
Print String in order of Keywords:
Life For Geeks
String operation
n Python, a string is an ordered sequence of Unicode characters.
Each character in the string has a unique index in the sequence. The
index starts with 0. First character in the string has its positional
index 0. The index keeps incrementing towards the end of string.
Python allows you to access any individual character from the string
by its index. In this case, 0 is the lower bound and 11 is the upper
bound of the string. So, var[0] returns H, var[6] returns P. If the
index in square brackets exceeds the upper bound, Python raises
IndexError.
>>> var[-1]
'N'
>>> var[-5]
'Y'
>>> var[-12]
'H'
>>> var[-13]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
var="HELLO PYTHON"
var[7]="y"
print (var)
substr=var[x:y]
The ":" operator needs two integer operands (both of which may be
omitted, as we shall see in subsequent examples). The first operand
x is the index of the first character of the desired slice. The second
operand y is the index of the character next to the last in the
desired string. So var(x:y] separates characters from xth position to
(y-1)th position from the original string.
var="HELLO PYTHON"
print ("var:",var)
print ("var[3:8]:", var[3:8])
var="HELLO PYTHON"
print ("var:",var)
print ("var[3:8]:", var[3:8])
print ("var[-9:-4]:", var[-9:-4])
Both the operands for Python's Slice operator are optional. The first
operand defaults to zero, which means if we do not give the first
operand, the slice starts of character at 0th index, i.e. the first
character. It slices the leftmost substring up to "y-1" characters.
var="HELLO PYTHON"
print ("var:",var)
print ("var[0:5]:", var[0:5])
print ("var[:5]:", var[:5])
var="HELLO PYTHON"
print ("var:",var)
print ("var[6:12]:", var[6:12])
print ("var[6:]:", var[6:])
str1="Hello"
str2="World"
print ("String 1:",str1)
print ("String 2:",str2)
str3=str1+str2
print("String 3:",str3)
It will produce the following output −
String 1: Hello
String 2: World
String 3: HelloWorld
str1="Hello"
str2="World"
blank=" "
print ("String 1:",str1)
print ("String 2:",str2)
str3=str1+blank+str2
print("String 3:",str3)
It will produce the following output −
String 1: Hello
String 2: World
String 3: Hello World
>>> "Hello"*3
'HelloHelloHello'
The integer operand is the number of copies of the string operand to
be concatenated.
Both the string operators, (*) the repetition operator and (+) the
concatenation operator, can be used in a single expression. The "*"
operator has a higher precedence over the "+" operator.
str1="Hello"
str2="World"
print ("String 1:",str1)
print ("String 2:",str2)
str3=str1+str2*3
print("String 3:",str3)
str4=(str1+str2)*3
print ("String 4:", str4)
To form str3 string, Python concatenates 3 copies of World first, and
then appends the result to Hello
String 3: HelloWorldWorldWorld
In the second case, the strings str1 and str2 are inside parentheses,
hence their concatenation takes place first. Its result is then
replicated three times.
String 4: HelloWorldHelloWorldHelloWorld
\<newline>
1
Backslash and newline ignored
\\
2
Backslash (\)
\'
3
Single quote (')
4 \"
Double quote (")
\a
5
ASCII Bell (BEL)
\b
6
ASCII Backspace (BS)
\f
7
ASCII Formfeed (FF)
\n
8
ASCII Linefeed (LF)
\r
9
ASCII Carriage Return (CR)
\t
10
ASCII Horizontal Tab (TAB)
\v
11
ASCII Vertical Tab (VT)
\ooo
12
Character with octal value ooo
\xhh
13
Character with hex value hh
Method Description
Formatting In string
Output
The mangy, scrawny stray dog hurriedly gobbled downthe
grain-free, organic dog food.
x = 'looked'
Output
Misha walked and looked around
Precision Handling in Python using % operator
Floating-point numbers use the format %a.bf. Here, a would be
the minimum number of digits to be present in the string;
these might be padded with white space if the whole number
doesn’t have this many digits.
Output
The value of pi is: 3.1416
variable = 12
string = "Variable as integer = %d \n\
Variable as float = %f" %(variable, variable)
print (string)
Output
Variable as integer = 12
Variable as float = 12.000000
Output
We all are equal.
Index-based Insertion
In this code, curly braces {} with indices are used within the
string ‘{2} {1} {0}’ to indicate the positions where the
corresponding values will be placed.
Output
Read the directions
print(
'The first {p} was alright, but the {p} {p} was
tough.'.format(p='second'))
Output
The first second was alright, but the second second was tough.
Both the codes are doing string formatting. The first String is
formatted with ‘%’ and the second String is formatted
with .format().
name = 'Ele'
print(f"My name is {name}.")
Output
My name is Ele.
This new formatting syntax is very powerful and easy. You can
also insert arbitrary Python expressions and you can even do
arithmetic operations in it.
Output
He said his age is 30.
Output
He said his age is 6
Float precision in the f-String Method
In this code, f-string formatting is used to interpolate the value
of the num variable into the string.
Syntax: {value:{width}.{precision}}
num = 3.14159
Output
The valueof pi is: 3.1416
n1 = 'Hello'
n2 = 'GeeksforGeeks'
Output
Hello ! This is GeeksforGeeks.
string = "GeeksForGeeks!"
width = 30
centered_string = string.center(width)
print(centered_string)
Output
GeeksForGeeks!
Similar Reads:
Regular Expressions
A Regular Expression or RegEx is a special sequence of characters
that uses a search pattern to find a string or set of strings.
It can detect the presence or absence of a text by matching it with a
particular pattern and also can split a pattern into one or more sub-
patterns.
# importing re module
import re
import re
Output
Start Index: 34
End Index: 40
Note: Here r character (r’portal’) stands for raw, not regex. The raw
string is slightly different from a regular string, it won’t interpret the \
character as an escape character. This is because the regular
expression engine uses \ character for its own escaping purpose.
Before starting with the Python regex module let’s see how to actually
write regex using metacharacters or special sequences.
Metacharacters
Metacharacters are the characters with special meaning.
To understand the RE analogy, Metacharacters are useful and
important. They will be used in functions of module re. Below is the
list of metacharacters.
MetaCharacters Description
Verbose
Practice
Jobs
In this article, we will learn about VERBOSE flag of the re
package and how to use it. re.VERBOSE : This flag allows you to write
regular expressions that look nicer and are more readable by allowing
you to visually separate logical sections of the pattern and add
comments. Whitespace within the pattern is ignored, except when in a
character class, or when preceded by an unescaped backslash, or
within tokens like *?, (?: or (?P. When a line contains a # that is not in
a character class and is not preceded by an unescaped backslash, all
characters from the leftmost such # through the end of the line are
ignored.
re.IGNORECASE)
# Using VERBOSE
regex_email = re.compile(r"""
@ # single @ sign
\. # single Dot .
""",re.VERBOSE | re.IGNORECASE)
Input : [email protected]@
Output : Invalid
This is invalid because there is @ after the top level domain
name.
module declaration
Python Modules
Read
Courses
Practice
Video
Jobs
Python Module is a file that contains built-in functions,
classes,its and variables. There are many Python modules, each with
its specific work.
In this article, we will cover all about Python modules, such as How to
create our own simple module, Import Python modules, From
statements in Python, we can use the alias to rename the module, etc.
What is Python Module
A Python module is a file containing Python definitions and statements.
A module can define functions, classes, and variables. A module can
also include runnable code.
Grouping related code into a module makes the code easier to
understand and use. It also makes the code logically organized.
Create a Python Module
To create a Python module, write the desired code and save that in a
file with .py extension. Let’s understand it better with an example:
Example:
Let’s create a simple calc.py in which we define two functions,
one add and another subtract.
Python3
return (x+y)
return (x-y)
Python3
import calc
print(calc.add(10, 2))
Output:
12
Python Import From Module
Python’s from statement lets you import specific attributes from a
module without importing the module as a whole.
Import Specific Attributes from a Python module
Here, we are importing specific sqrt and factorial attributes from the
math module.
Python3
# module math
# are required.
print(sqrt(16))
print(factorial(6))
Output:
4.0
720
Import all Names
The * symbol used with the import statement is used to import all the
names from a module to a current namespace.
Syntax:
from module_name import *
What does import * do in Python?
The use of * has its advantages and disadvantages. If you know exactly
what you will be needing from the module, it is not recommended to
use *, else do so.
Python3
# module math
# are required.
print(sqrt(16))
print(factorial(6))
Output
4.0
720
Locating Python Modules
Whenever a module is imported in Python the interpreter looks for
several locations. First, it will check for the built-in module, if not found
then it looks for a list of directories defined in the sys.path. Python
interpreter searches for the module in the following manner –
First, it searches for the module in the current directory.
If the module isn’t found in the current directory, Python then
searches each directory in the shell variable PYTHONPATH. The
PYTHONPATH is an environment variable, consisting of a list of
directories.
If that also fails python checks the installation-dependent list
of directories configured at the time Python is installed.
Directories List for Modules
Here, sys.path is a built-in variable within the sys module. It contains a
list of directories that the interpreter will search for the required
module.
Python3
import sys
# importing sys.path
print(sys.path)
Output:
[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/python38.zip’, ‘/usr/lib/python3.8’,
‘/usr/lib/python3.8/lib-dynload’, ”,
‘/home/nikhil/.local/lib/python3.8/site-packages’,
‘/usr/local/lib/python3.8/dist-packages’, ‘/usr/lib/python3/dist-
packages’, ‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’,
‘/home/nikhil/.ipython’]
Renaming the Python Module
We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name
Python3
# module math
import math as mt
print(mt.sqrt(16))
print(mt.factorial(6))
Output
4.0
720
import math
# in math module
print(math.sqrt(25))
print(math.pi)
print(math.degrees(2))
# 60 degrees = 1.04 radians
print(math.radians(60))
# Sine of 2 radians
print(math.sin(2))
print(math.cos(0.5))
print(math.tan(0.23))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
import random
print(random.randint(0, 5))
print(random.random())
print(random.random() * 100)
List = [1, 4, True, 800, "python", 27, "hello"]
print(random.choice(List))
import datetime
import time
print(time.time())
print(date.fromtimestamp(454554))
Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87
We have covered Python Modules and it’s operations like create,
import, etc. This article will give the overview about Python modules so
that you can easily create and use modules in Python.
https://www.programiz.com/python-
programming/function
Objects
An Object is an instance of a Class. A class is like a blueprint while an
instance is a copy of the class with actual values. Python is an object-
oriented programming language that stresses objects i.e. it mainly
emphasizes functions. Python Objects are basically an encapsulation
of data variables and methods acting on that data into a single entity.
Note: For more information, Python Classes and Objects
Understanding of Python Object
For a better understanding of the concept of objects in Python. Let’s
consider an example, many of you have played CLASH OF CLANS, So
let’s assume base layout as the class which contains all the buildings,
defenses, resources, etc. Based on these descriptions we make a
village, here the village is the object in Python.
Syntax:
obj = MyClass()
print(obj.x)
Instance defining represent memory allocation necessary for storing
the actual data of variables. Each time when you create an object of
class a copy of each data variable defined in that class is created. In
simple language, we can state that each object of a class has its own
copy of data members defined in that class.
Creating a Python Object
Working of the Program: Audi = Cars()
A block of memory is allocated on the heap. The size of
memory allocated is decided by the attributes and methods
available in that class(Cars).
After the memory block is allocated, the special
method __init__() is called internally. Initial data is stored in
the variables through this method.
The location of the allocated memory address of the instance
is returned to the object(Cars).
The memory location is passed to self.
Python3
class Cars:
def __init__(self, m, p):
self.model = m
self.price = p
print(Audi.model)
print(Audi.price)
Output:
R8
100000
Exceptions
Python Exceptions
When a Python program meets an error, it stops the execution of the rest of
the program. An error in Python might be either an error in the syntax of an
expression or a Python exception. We will see what an exception is. Also, we
will see the difference between a syntax error and an exception in this
tutorial. Following that, we will learn about trying and except blocks and how
to raise exceptions and make assertions. After that, we will see the Python
exceptions list.
What is an Exception?
An exception in Python is an incident that happens while executing a
program that causes the regular course of the program's commands to be
disrupted. When a Python code comes across a condition it can't handle, it
raises an exception. An object in Python that describes an error is called an
exception.
When a Python code throws an exception, it has two options: handle the
exception immediately or stop and quit.
Code
1. #Python code after removing the syntax error
2. string = "Python Exceptions"
3.
4. for s in string:
5. if (s != o:
6. print( s )
Output:
if (s != o:
^
SyntaxError: invalid syntax
The arrow in the output shows where the interpreter encountered a syntactic
error. There was one unclosed bracket in this case. Close it and rerun the
program:
Code
Output:
ADVERTISEMENT
ADVERTISEMENT
Code
1. # Python code to catch an exception and handle it using try and excep
t code blocks
2.
3. a = ["Python", "Exceptions", "try and except"]
4. try:
5. #looping through the elements of the array a, choosing a range that
goes beyond the length of the array
6. for i in range( 4 ):
7. print( "The index and element from the array is", i, a[i] )
8. #if an error occurs in the try block, then except block will be executed by the
Python interpreter
9. except:
10. print ("Index out of range")
Output:
The code blocks that potentially produce an error are inserted inside the try
clause in the preceding example. The value of i greater than 2 attempts to
access the list's item beyond its length, which is not present, resulting in an
exception. The except clause then catches this exception and executes code
without stopping it.
Code
Output:
1 num = [3, 4, 5, 7]
2 if len(num) > 3:
----> 3 raise Exception( f"Length of the given list must be less than or
equal to 3 but is {len(num)}" )
Exception: Length of the given list must be less than or equal to 3 but is 4
The implementation stops and shows our exception in the output, providing
indications as to what went incorrect.
Assertions in Python
When we're finished verifying the program, an assertion is a consistency test
that we can switch on or off.
Assertions are made via the assert statement, which was added in Python
1.5 as the latest keyword.
ADVERTISEMENT
ADVERTISEMENT
Code
Output:
Code
1. # Python program to show how to use else clause with try and except
clauses
2.
3. # Defining a function which returns reciprocal of a number
4. def reciprocal( num1 ):
5. try:
6. reci = 1 / num1
7. except ZeroDivisionError:
8. print( "We cannot divide by zero" )
9. else:
10. print ( reci )
11. # Calling the function and passing values
12.reciprocal( 4 )
13. reciprocal( 0 )
Output:
0.25
We cannot divide by zero
Code
Output:
User-Defined Exceptions
By inheriting classes from the typical built-in exceptions, Python also lets us
design our customized exceptions.
We raise a user-defined exception in the try block and then handle the
exception in the except block. An example of the class EmptyError is created
using the variable var.
Code
Output:
2 try:
----> 3 raise EmptyError( "The variable is empty" )
4 except (EmptyError, var):
2 StopIteration If the next() method returns null for an iterator, this exception is
4 StandardError Excluding the StopIteration and SystemExit, this is the base cla
built-in exceptions.
8 ZeroDivisionError For all numeric data types, its value is raised whenever a numb
to be divided by zero.
9 AssertionError If the Assert statement fails, this exception is raised.
11 EOFError When the endpoint of the file is approached, and the interprete
input value by raw_input() or input() functions, this exception is
16 KeyError When the given key is not found in the dictionary to be found in
is raised.
19 EnvironmentError All exceptions that arise beyond the Python environment have t
20 IOError If an input or output action fails, like when using the print c
open() function to access a file that does not exist, this exceptio
Summary
We learned about different methods to raise, catch, and handle Python
exceptions after learning the distinction between syntax errors and
exceptions. We learned about these clauses in this tutorial:
o We can throw an exception at any line of code using the raise keyword.
o Using the assert keyword, we may check to see if a specific condition is
fulfilled and raise an exception if it is not.
o All statements are carried out in the try clause until an exception is found.
o The try clause's exception(s) are detected and handled using the except
function.
o If no exceptions are thrown in the try code block, we can write code to be
executed in the else code block.
Lambda Functions
Python Lambda Functions are anonymous functions means that
the function is without a name. As we already know the def keyword
is used to define a normal function in Python. Similarly,
the lambda keyword is used to define an anonymous function
in Python.
Python Lambda Function Syntax
Syntax: lambda arguments : expression
This function can have any number of arguments but only
one expression, which is evaluated and returned.
One is free to use lambda functions wherever function objects
are required.
You need to keep in your knowledge that lambda functions
are syntactically restricted to a single expression.
It has various uses in particular fields of programming,
besides other types of expressions in functions.
str1 = 'GeeksforGeeks'
Output:
GEEKSFORGEEKS
Use of Lambda Function in Python
Let’s see some of the practical uses of the Python lambda function.
Condition Checking Using Python lambda function
Here, the ‘format_numric’ calls the lambda function, and the num is
passed as a parameter to perform operations.
Python3
Output:
Int formatting: 1.000000e+06
float formatting: 999,999.79
Difference Between Lambda functions and def defined
function
The code defines a cube function using both the ‘def' keyword and a
lambda function. It calculates the cube of a given number (5 in this
case) using both approaches and prints the results. The output is 125
for both the ‘def' and lambda functions, demonstrating that they
achieve the same cube calculation.
Python3
def cube(y):
return y*y*y
Output:
Using function defined with `def` keyword, cube: 125
Using lambda function, cube: 125
As we can see in the above example, both the cube() function
and lambda_cube() function behave the same and as intended. Let’s
analyze the above example a bit more:
With lambda function Without lambda function
Good for performing short Good for any cases that require
operations/data manipulations. multiple lines of code.
Python Classes
A class is considered a blueprint of objects.
We can think of the class as a sketch (prototype) of a house. It contains all the
details about the floors, doors, windows, etc.
Based on these descriptions, we build the house; the house is the object.
Since many houses can be made from the same description, we can create
many objects from a class.
Define Python Class
We use the class keyword to create a class in Python. For example,
class ClassName:
# class definition
class Bike:
name = ""
gear = 0
Here,
Python Objects
An object is called an instance of a class.
Suppose Bike is a class then we can create objects like bike1 , bike2 , etc from
the class.
Here's the syntax to create an object.
objectName = ClassName()
# create class
class Bike:
name = ""
gear = 0
Here, bike1 is the object of the class. Now, we can use this object to access
the class attributes.
Here, we have used bike1.name and bike1.gear to change and access the
value of name and gear attributes, respectively.
Example 1: Python Class and Objects
# define a class
class Bike:
name = ""
gear = 0
Output
In the above example, we have defined the class named Bike with two
attributes: name and gear .
# define a class
class Employee:
# define a property
employee_id = 0
Output
Python Methods
We can also define a function inside a Python class. A Python function
defined inside a class is called a method.
Let's see an example,
# create a class
class Room:
length = 0.0
breadth = 0.0
Output
2. Method: calculate_area()
Here, we have created an object named study_room from the Room class.
We then used the object to assign values to attributes: length and breadth .
Notice that we have also used the object to call the method inside the class,
study_room.calculate_area()
Here, we have used the . notation to call the method. Finally, the statement
inside the method is executed.
Python Constructors
Earlier we assigned a default value to a class attribute,
class Bike:
name = ""
...
# create object
bike1 = Bike()
However, we can also initialize values using the constructors. For example,
class Bike:
# constructor function
def __init__(self, name = ""):
self.name = name
bike1 = Bike()
https://www.geeksforgeeks.org/python-classes-and-objects/
instance methods
# classes
class Person:
self.name = name
# Sample Method
def say_hi(self):
p = Person('Nikhil')
p.say_hi()
Output:
Hello, my name is Nikhil
Note: For more information, refer to Python Classes and Objects
Instance Method
Instance attributes are those attributes that are not shared by objects.
Every object has its own copy of the instance attribute. For example,
consider a class shapes that have many objects like circle, square,
triangle, etc. having its own attributes and methods. An instance
attribute refers to the properties of that particular object like edge of
the triangle being 3, while the edge of the square can be 4. An
instance method can access and even modify the value of attributes of
an instance. It has one default parameter:-
self – It is a keyword which points to the current passed
instance. But it need not be passed every time while calling an
instance method.
Example:
# instance methods
class shape:
# Calling Constructor
self.edge = edge
self.color = color
# Instance Method
def finEdges(self):
return self.edge
# Instance Method
self.edge = newedge
# Driver Code
square.modifyEdges(6)
Output
No. of edges for circle: 0
No. of edges for square: 6
Don't miss your chance to ride the wave of the data revolution! Every
industry is scaling new heights by tapping into the power of data.
Sharpen your skills and become a part of the hottest trend in the 21st
century.
Dive into the future of technology - explore the Complete Machine
Learning and Data Science Program by GeeksforGeeks and stay ahead
of the curve.
Instance Variables
Instance Variables:Instance variables are unique to each instance of a class.
They are defined within methods and are prefixed with the self keyword. These
variables store data that is specific to an instance, making them essential for
object-oriented programming (OOP) principles like encapsulation.
Closures
Python Closures
Python closure is a nested function that allows us to access variables of the
outer function even after the outer function is closed.
Before we learn about closure, let's first revise the concept of nested functions
in Python.
def greet(name):
# inner function
def display_name():
print("Hi", name)
# Output: Hi John
Run Code
def greet():
# variable defined outside the inner function
name = "John"
# Output: Hi John
Run Code
In the above example, we have created a function named greet() that returns
a nested anonymous function.
Here, when we call the outer function,
message = greet()
Output
3
5
7
3
odd = calculate()
This code executes the outer function calculate() and returns a closure to the
odd number. T
That's why we can access the num variable of calculate() even after
completing the outer function.
Again, when we call the outer function using
odd2 = calculate()
Closures can be used to avoid global values and provide data hiding, and can
be an elegant solution for simple cases with one or few methods.
However, for larger cases with multiple attributes and methods, a class
implementation may be more appropriate.
def make_multiplier_of(n):
def multiplier(x):
return x * n
return multiplier
# Multiplier of 3
times3 = make_multiplier_of(3)
# Multiplier of 5
times5 = make_multiplier_of(5)
# Output: 27
print(times3(9))
# Output: 15
print(times5(3))
# Output: 30
print(times5(times3(2)))
Run Code
All function objects have a __closure__ attribute that returns a tuple of cell
objects if it is a closure function.
Generators
Python Generators
In Python, a generator is a function that returns an iterator that produces a
sequence of values when iterated over.
Generators are useful when we want to produce a large sequence of values,
but we don't want to store all of them in memory at once.
Create Python Generator
In Python, similar to defining a normal function, we can define a generator
function using the def keyword, but instead of the return statement we use
the yield statement.
def generator_name(arg):
# statements
yield something
Here, the yield keyword is used to produce a value from the generator.
When the generator function is called, it does not execute the function body
immediately. Instead, it returns a generator object that can be iterated over to
produce the values.
def my_generator(n):
# initialize counter
value = 0
Output
0
1
2
and the print statement prints each value produced by the generator.
We can also create a generator object from the generator function by calling
the function like we would any other function as,
generator = my_range(3)
print(next(generator)) # 0
print(next(generator)) # 1
print(next(generator)) # 2
Here, expression is a value that will be returned for each item in the iterable .
The generator expression creates a generator object that produces the values
of expression for each item in the iterable , one at a time, when iterated over.
Output
0
1
4
9
16
Here, we have created the generator object that will produce the squares of
the numbers 0 through 4 when iterated over.
And then, to iterate over the generator and get the values, we have used
the for loop.
1. Easy to Implement
class PowTwo:
def __init__(self, max=0):
self.n = 0
self.max = max
def __iter__(self):
return self
def __next__(self):
if self.n > self.max:
raise StopIteration
result = 2 ** self.n
self.n += 1
return result
The above program was lengthy and confusing. Now, let's do the same using
a generator function.
def PowTwoGen(max=0):
n = 0
while n < max:
yield 2 ** n
n += 1
2. Memory Efficient
The following generator function can generate all the even numbers (at least
in theory).
def all_even():
n = 0
while True:
yield n
n += 2
4. Pipelining Generators
def fibonacci_numbers(nums):
x, y = 0, 1
for _ in range(nums):
x, y = y, x+y
yield x
def square(nums):
for num in nums:
yield num**2
print(sum(square(fibonacci_numbers(10))))
# Output: 4895
Run Code
This pipelining is efficient and easy to read (and yes, a lot cooler!).
Iterators
Iterators in Python
Read
Courses
Practice
Jobs
An iterator in Python is an object that is used to iterate over iterable
objects like lists, tuples, dicts, and sets. The Python iterators object is
initialized using the iter() method. It uses the next() method for
iteration.
1. __iter__(): The iter() method is called for the initialization of an
iterator. This returns an iterator object
2. __next__(): The next method returns the next value for the
iterable. When we use a for loop to traverse any iterable
object, internally it uses the iter() method to get an iterator
object, which further uses the next() method to iterate over.
This method raises a StopIteration to signal the end of the
iteration.
Python iter() Example
Python3
string = "GFG"
ch_iterator = iter(string)
print(next(ch_iterator))
print(next(ch_iterator))
print(next(ch_iterator))
Output :
G
F
G
Creating and looping over an iterator using iter() and
next()
Python3
class Test:
# Constructor
self.limit = limit
def __iter__(self):
self.x = 10
return self
def __next__(self):
# Store current value ofx
x = self.x
if x > self.limit:
raise StopIteration
self.x = x + 1;
return x
for i in Test(15):
print(i)
# Prints nothing
for i in Test(5):
print(i)
Output:
10
11
12
13
14
15
print("List Iteration")
for i in l:
print(i)
print("\nTuple Iteration")
for i in t:
print(i)
print("\nString Iteration")
s = "Geeks"
for i in s :
print(i)
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
Output:
List Iteration
geeks
for
geeks
Tuple Iteration
geeks
for
geeks
String Iteration
G
e
e
k
s
Dictionary Iteration
xyz 123
abc 345
Iterable vs Iterator
Python iterable and Python iterator are different. The main difference
between them is, iterable in Python cannot save the state of the
iteration, whereas in iterators the state of the current iteration gets
saved.
Note: Every iterator is also an iterable, but not every iterable is an
iterator in Python.
Read more – Difference between iterable and iterator.
Iterating on an Iterable
Python3
print(item)
Output:
a
b
c
d
e
Iterating on an iterator
Python3
tup_iter = iter(tup)
print("Inside loop:")
print(item)
if index == 2:
break
print("Outside loop:")
print(next(tup_iter))
print(next(tup_iter))
Output:
Inside loop:
a
b
c
Outside loop:
d
e
Python3
iterable = (1, 2, 3, 4)
iterator_obj = iter(iterable)
# iterating on iterable
print(item, end=",")
print(item, end=",")
print("\nIterating on an iterator:")
print(item, end=",")
print(next(iterator_obj))
Output:
Iterable loop 1:
1,2,3,4,
Iterable Loop 2:
1,2,3,4,
Iterating on an iterator:
1,2,3,4,
Iterator: Outside loop
Don't miss your chance to ride the wave of the data revolution! Every
industry is scaling new heights by tapping into the power of data.
Sharpen your skills and become a part of the hottest trend in the 21st
century
Generator Expressions
Courses
Practice
Jobs
In Python, to create iterators, we can use both regular functions and
generators. Generators are written just like a normal function but we
use yield() instead of return() for returning a result. It is more powerful
as a tool to implement iterators. It is easy and more convenient to
implement because it offers the evaluation of elements on demand.
Unlike regular functions which on encountering a return statement
terminates entirely, generators use a yield statement in which the
state of the function is saved from the last call and can be picked up or
resumed the next time we call a generator function. Another great
advantage of the generator over a list is that it takes much less
memory.
In addition to that, two more functions _next_() and _iter_() make the
generator function more compact and reliable. Example :
Python3
def generator():
t = 1
yield t
t += 1
yield t
t += 1
yield t
call = generator()
next(call)
next(call)
next(call)
Output :
First result is 1
Second result is 2
Third result is 3
print(num)
Output :
0
1
4
9
16
25
36
49
64
81
print(li)
Output:
['k', 'e', 'e', 'g']