Python provides the datetime module work with real dates and times. In real-world applications, we need to work with the date and time. Python enables us to schedule our Python script to run at a particular timing.
In Python, the date is not a data type, but we can work with the date objects by importing the module named with datetime, time, and calendar.
In this section of the tutorial, we will discuss how to work with the date and time objects in Python.
The datetime classes are classified in the six main classes.
date – It is a naive ideal date. It consists of the year, month, and day as attributes.
time – It is a perfect time, assuming every day has precisely 24*60*60 seconds. It has hour, minute, second, microsecond, and tzinfo as attributes.
datetime – It is a grouping of date and time, along with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo.
timedelta – It represents the difference between two dates, time or datetime instances to microsecond resolution.
tzinfo – It provides time zone information objects.
timezone – It is included in the new version of Python. It is the class that implements the tzinfo abstract base class.
Tick
In Python, the time instants are counted since 12 AM, 1st January 1970. The function time() of the module time returns the total number of ticks spent since 12 AM, 1st January 1970. A tick can be seen as the smallest unit to measure the time.
Consider the following example
import time;
#prints the number of ticks spent since 12 AM, 1st January 1970
print(time.time())
Output:1585928913.6519969
How to get the current time?
The localtime() functions of the time module are used to get the current time tuple. Consider the following example.
Example
import time;
#returns a time tuple
print(time.localtime(time.time()))
The time is treated as the tuple of 9 numbers. Let’s look at the members of the time tuple.
Index
Attribute
Values
0
Year
4 digit (for example 2018)
1
Month
1 to 12
2
Day
1 to 31
3
Hour
0 to 23
4
Minute
0 to 59
5
Second
0 to 60
6
Day of weak
0 to 6
7
Day of year
1 to 366
8
Daylight savings
-1, 0, 1 , or -1
Getting formatted time
The time can be formatted by using the asctime() function of the time module. It returns the formatted time for the time tuple being passed.
Example
import time
#returns the formatted time
print(time.asctime(time.localtime(time.time())))
Output:Tue Dec 18 15:31:39 2018
Python sleep time
The sleep() method of time module is used to stop the execution of the script for a given amount of time. The output will be delayed for the number of seconds provided as the float.
Consider the following example.
Example
import time
for i in range(0,5):
print(i)
#Each element will be printed after 1 second
time.sleep(1)
Output:0 1 2 3 4
The datetime Module
The datetime module enables us to create the custom date objects, perform various operations on dates like the comparison, etc.
To work with dates as date objects, we have to import the datetime module into the python source code.
Consider the following example to get the datetime object representation for the current time.
Example
import datetime
#returns the current datetime object
print(datetime.datetime.now())
Output:2020-04-04 13:18:35.252578
Creating date objects
We can create the date objects bypassing the desired date in the datetime constructor for which the date objects are to be created.
Consider the following example.
Example
import datetime
#returns the datetime object for the specified date
print(datetime.datetime(2020,04,04))
Output:2020-04-04 00:00:00
We can also specify the time along with the date to create the datetime object. Consider the following example.
Example
import datetime
#returns the datetime object for the specified time
print(datetime.datetime(2020,4,4,1,26,40))
Output:2020-04-04 01:26:40
In the above code, we have passed in datetime() function year, month, day, hour, minute, and millisecond attributes in a sequential manner.
Comparison of two dates
We can compare two dates by using the comparison operators like >, >=, <, and <=.
Consider the following example.
Example
from datetime import datetime as dt
#Compares the time. If the time is in between 8AM and 4PM, then it prints working hours otherwise it prints fun hours
if dt(dt.now().year,dt.now().month,dt.now().day,8)<dt.now()<dt(dt.now().year,dt.now().month,dt.now().day,16):
print("Working hours....")
else:
print("fun hours")
Output:fun hours
The calendar module
Python provides a calendar object that contains various methods to work with the calendars.
Consider the following example to print the calendar for the last month of 2018.
Example
import calendar;
cal = calendar.month(2020,3)
#printing the calendar of December 2018
print(cal)
Output:March 2020 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Printing the calendar of whole year
The prcal() method of calendar module is used to print the calendar of the entire year. The year of which the calendar is to be printed must be passed into this method.
Example
import calendar
#printing the calendar of the year 2019
s = calendar.prcal(2020)
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.
Exceptions versus Syntax Errors
When the interpreter identifies a statement that has an error, syntax errors occur. Consider the following scenario:
Code
#Python code after removing the syntax error
string = "Python Exceptions"
for s in string:
if (s != o:
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
#Python code after removing the syntax error
string = "Python Exceptions"
for s in string:
if (s != o):
print( s )
Output: 2 string = “Python Exceptions” 4 for s in string: —-> 5 if (s != o): 6 print( s ) NameError: name ‘o’ is not defined
We encountered an exception error after executing this code. When syntactically valid Python code produces an error, this is the kind of error that arises. The output’s last line specified the name of the exception error code encountered. Instead of displaying just “exception error”, Python displays information about the sort of exception error that occurred. It was a NameError in this situation. Python includes several built-in exceptions. However, Python offers the facility to construct custom exceptions.
Try and Except Statement – Catching Exceptions
In Python, we catch exceptions and handle them using try and except code blocks. The try clause contains the code that can raise an exception, while the except clause contains the code lines that handle the exception. Let’s see if we can access the index from the array, which is more than the array’s length, and handle the resulting exception.
Code
# Python code to catch an exception and handle it using try and except code blocks
a = ["Python", "Exceptions", "try and except"]
try:
#looping through the elements of the array a, choosing a range that goes beyond the length of the array
for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
#if an error occurs in the try block, then except block will be executed by the Python interpreter
except:
print ("Index out of range")
Output:The index and element from the array is 0 Python The index and element from the array is 1 Exceptions The index and element from the array is 2 try and except Index out of range
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.
How to Raise an Exception
If a condition does not meet our criteria but is correct according to the Python interpreter, we can intentionally raise an exception using the raise keyword. We can use a customized exception in conjunction with the statement.
If we wish to use raise to generate an exception when a given condition happens, we may do so as follows:
Code
#Python code to show how to raise an exception in Python
num = [3, 4, 5, 7]
if len(num) > 3:
raise Exception( f"Length of the given list must be less than or equal to 3 but is {len(num)}" )
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.
The simplest way to understand an assertion is to compare it with an if-then condition. An exception is thrown if the outcome is false when an expression is evaluated.
Assertions are made via the assert statement, which was added in Python 1.5 as the latest keyword.
Assertions are commonly used at the beginning of a function to inspect for valid input and at the end of calling the function to inspect for valid output.
The assert Statement
Python examines the adjacent expression, preferably true when it finds an assert statement. Python throws an AssertionError exception if the result of the expression is false.
The syntax for the assert clause is −
assert Expressions[, Argument]
Python uses ArgumentException, if the assertion fails, as the argument for the AssertionError. We can use the try-except clause to catch and handle AssertionError exceptions, but if they aren’t, the program will stop, and the Python interpreter will generate a traceback.
Code
#Python program to show how to use assert keyword
# defining a function
def square_root( Number ):
assert ( Number < 0), "Give a positive integer"
return Number**(1/2)
#Calling function and passing the values
print( square_root( 36 ) )
print( square_root( -36 ) )
Output: 7 #Calling function and passing the values —-> 8 print( square_root( 36 ) ) 9 print( square_root( -36 ) ) Input In [23], in square_root(Number) 3 def square_root( Number ): —-> 4 assert ( Number < 0), “Give a positive integer” 5 return Number**(1/2) AssertionError: Give a positive integer
Try with Else Clause
Python also supports the else clause, which should come after every except clause, in the try, and except blocks. Only when the try clause fails to throw an exception the Python interpreter goes on to the else block.
Here is an instance of a try clause with an else clause.
Code
# Python program to show how to use else clause with try and except clauses
# Defining a function which returns reciprocal of a number
def reciprocal( num1 ):
try:
reci = 1 / num1
except ZeroDivisionError:
print( "We cannot divide by zero" )
else:
print ( reci )
# Calling the function and passing values
reciprocal( 4 )
reciprocal( 0 )
Output:0.25 We cannot divide by zero
Finally Keyword in Python
The finally keyword is available in Python, and it is always used after the try-except block. The finally code block is always executed after the try block has terminated normally or after the try block has terminated for some other reason.
Here is an example of finally keyword with try-except clauses:
Code
# Python code to show the use of finally clause
# Raising an exception in try block
try:
div = 4 // 0
print( div )
# this block will handle the exception raised
except ZeroDivisionError:
print( "Atepting to divide by zero" )
# this will always be executed no matter exception is raised or not
finally:
print( 'This is code of finally clause' )
Output:Atepting to divide by zero This is code of finally clause
User-Defined Exceptions
By inheriting classes from the typical built-in exceptions, Python also lets us design our customized exceptions.
Here is an illustration of a RuntimeError. In this case, a class that derives from RuntimeError is produced. Once an exception is detected, we can use this to display additional detailed information.
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
class EmptyError( RuntimeError ):
def __init__(self, argument):
self.arguments = argument
Once the preceding class has been created, the following is how to raise an exception:
Code
var = " "
try:
raise EmptyError( "The variable is empty" )
except (EmptyError, var):
print( var.arguments )
Output: 2 try: —-> 3 raise EmptyError( “The variable is empty” ) 4 except (EmptyError, var): EmptyError: The variable is empty
Python Exceptions List
Here is the complete list of Python in-built exceptions.
Sr.No.
Name of the Exception
Description of the Exception
1
Exception
All exceptions of Python have a base class.
2
StopIteration
If the next() method returns null for an iterator, this exception is raised.
3
SystemExit
The sys.exit() procedure raises this value.
4
StandardError
Excluding the StopIteration and SystemExit, this is the base class for all Python built-in exceptions.
5
ArithmeticError
All mathematical computation errors belong to this base class.
6
OverflowError
This exception is raised when a computation surpasses the numeric data type’s maximum limit.
7
FloatingPointError
If a floating-point operation fails, this exception is raised.
8
ZeroDivisionError
For all numeric data types, its value is raised whenever a number is attempted to be divided by zero.
9
AssertionError
If the Assert statement fails, this exception is raised.
10
AttributeError
This exception is raised if a variable reference or assigning a value fails.
11
EOFError
When the endpoint of the file is approached, and the interpreter didn’t get any input value by raw_input() or input() functions, this exception is raised.
12
ImportError
This exception is raised if using the import keyword to import a module fails.
13
KeyboardInterrupt
If the user interrupts the execution of a program, generally by hitting Ctrl+C, this exception is raised.
14
LookupError
LookupErrorBase is the base class for all search errors.
15
IndexError
This exception is raised when the index attempted to be accessed is not found.
16
KeyError
When the given key is not found in the dictionary to be found in, this exception is raised.
17
NameError
This exception is raised when a variable isn’t located in either local or global namespace.
18
UnboundLocalError
This exception is raised when we try to access a local variable inside a function, and the variable has not been assigned any value.
19
EnvironmentError
All exceptions that arise beyond the Python environment have this base class.
20
IOError
If an input or output action fails, like when using the print command or the open() function to access a file that does not exist, this exception is raised.
22
SyntaxError
This exception is raised whenever a syntax error occurs in our program.
23
IndentationError
This exception was raised when we made an improper indentation.
24
SystemExit
This exception is raised when the sys.exit() method is used to terminate the Python interpreter. The parser exits if the situation is not addressed within the code.
25
TypeError
This exception is raised whenever a data type-incompatible action or function is tried to be executed.
26
ValueError
This exception is raised if the parameters for a built-in method for a particular data type are of the correct type but have been given the wrong values.
27
RuntimeError
This exception is raised when an error that occurred during the program’s execution cannot be classified.
28
NotImplementedError
If an abstract function that the user must define in an inherited class is not defined, this exception is raised.
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:
We can throw an exception at any line of code using the raise keyword.
Using the assert keyword, we may check to see if a specific condition is fulfilled and raise an exception if it is not.
All statements are carried out in the try clause until an exception is found.
The try clause’s exception(s) are detected and handled using the except function.
If no exceptions are thrown in the try code block, we can write code to be executed in the else code block.
Here is the syntax of try, except, else, and finally clauses.
Syntax:
try:
# Code block
# These statements are those which can probably have some error
except:
# This block is optional.
# If the try block encounters an exception, this block will handle it.
else:
# If there is no exception, this code block will be executed by the Python interpreter
finally:
# Python interpreter will always execute this code.
Modular programming is the practice of segmenting a single, complicated coding task into multiple, simpler, easier-to-manage sub-tasks. We call these subtasks modules. Therefore, we can build a bigger program by assembling different modules that act like building blocks.
Modularizing our code in a big application has a lot of benefits.
Simplification: A module often concentrates on one comparatively small area of the overall problem instead of the full task. We will have a more manageable design problem to think about if we are only concentrating on one module. Program development is now simpler and much less vulnerable to mistakes.
Flexibility: Modules are frequently used to establish conceptual separations between various problem areas. It is less likely that changes to one module would influence other portions of the program if modules are constructed in a fashion that reduces interconnectedness. (We might even be capable of editing a module despite being familiar with the program beyond it.) It increases the likelihood that a group of numerous developers will be able to collaborate on a big project.
Reusability: Functions created in a particular module may be readily accessed by different sections of the assignment (through a suitably established api). As a result, duplicate code is no longer necessary.
Scope: Modules often declare a distinct namespace to prevent identifier clashes in various parts of a program.
In Python, modularization of the code is encouraged through the use of functions, modules, and packages.
What are Modules in Python?
A document with definitions of functions and various statements written in Python is called a Python module.
In Python, we can define a module in one of 3 ways:
Python itself allows for the creation of modules.
Similar to the re (regular expression) module, a module can be primarily written in C programming language and then dynamically inserted at run-time.
A built-in module, such as the itertools module, is inherently included in the interpreter.
A module is a file containing Python code, definitions of functions, statements, or classes. An example_module.py file is a module we will create and whose name is example_module.
We employ modules to divide complicated programs into smaller, more understandable pieces. Modules also allow for the reuse of code.
Rather than duplicating their definitions into several applications, we may define our most frequently used functions in a separate module and then import the complete module.
Let’s construct a module. Save the file as example_module.py after entering the following.
Example:
# Here, we are creating a simple Python program to show how to create a module.
# defining a function in the module to reuse it
def square( number ):
# here, the above function will square the number passed as the input
result = number ** 2
return result # here, we are returning the result of the function
Here, a module called example_module contains the definition of the function square(). The function returns the square of a given number.
How to Import Modules in Python?
In Python, we may import functions from one module into our program, or as we say into, another module.
For this, we make use of the import Python keyword. In the Python window, we add the next to import keyword, the name of the module we need to import. We will import the module we defined earlier example_module.
Syntax:
import example_module
The functions that we defined in the example_module are not immediately imported into the present program. Only the name of the module, i.e., example_ module, is imported here.
We may use the dot operator to use the functions using the module name. For instance:
Example:
# here, we are calling the module square method and passing the value 4
result = example_module.square( 4 )
print("By using the module square of number is: ", result )
Output:By using the module square of number is: 16
There are several standard modules for Python. The complete list of Python standard modules is available. The list can be seen using the help command.
Similar to how we imported our module, a user-defined module, we can use an import statement to import other standard modules.
Importing a module can be done in a variety of ways. Below is a list of them.
Python import Statement
Using the import Python keyword and the dot operator, we may import a standard module and can access the defined functions within it. Here’s an illustration.
Code
# Here, we are creating a simple Python program to show how to import a standard module
# Here, we are import the math module which is a standard module
import math
print( "The value of euler's number is", math.e )
# here, we are printing the euler's number from the math module
Output:The value of euler’s number is 2.718281828459045
Importing and also Renaming
While importing a module, we can change its name too. Here is an example to show.
Code
# Here, we are creating a simple Python program to show how to import a module and rename it
# Here, we are import the math module and give a different name to it
import math as mt # here, we are importing the math module as mt
print( "The value of euler's number is", mt.e )
# here, we are printing the euler's number from the math module
Output:The value of euler’s number is 2.718281828459045
The math module is now named mt in this program. In some situations, it might help us type faster in case of modules having long names.
Please take note that now the scope of our program does not include the term math. Thus, mt.pi is the proper implementation of the module, whereas math.pi is invalid.
Python from…import Statement
We can import specific names from a module without importing the module as a whole. Here is an example.
Code
# Here, we are creating a simple Python program to show how to import specific
# objects from a module
# Here, we are import euler's number from the math module using the from keyword
from math import e
# here, the e value represents the euler's number
print( "The value of euler's number is", e )
Output:The value of euler’s number is 2.718281828459045
Only the e constant from the math module was imported in this case.
We avoid using the dot (.) operator in these scenarios. As follows, we may import many attributes at the same time:
Code
# Here, we are creating a simple Python program to show how to import multiple
# objects from a module
from math import e, tau
print( "The value of tau constant is: ", tau )
print( "The value of the euler's number is: ", e )
Output:The value of tau constant is: 6.283185307179586 The value of the euler’s number is: 2.718281828459045
Import all Names – From import * Statement
To import all the objects from a module within the present namespace, use the * symbol and the from and import keyword.
Syntax:
from name_of_module import *
There are benefits and drawbacks to using the symbol *. It is not advised to use * unless we are certain of our particular requirements from the module; otherwise, do so.
Here is an example of the same.
Code
# Here, we are importing the complete math module using *
from math import *
# Here, we are accessing functions of math module without using the dot operator
print( "Calculating square root: ", sqrt(25) )
# here, we are getting the sqrt method and finding the square root of 25
print( "Calculating tangent of an angle: ", tan(pi/6) )
# here pi is also imported from the math module
Output:Calculating square root: 5.0 Calculating tangent of an angle: 0.5773502691896257
Locating Path of Modules
The interpreter searches numerous places when importing a module in the Python program. Several directories are searched if the built-in module is not present. The list of directories can be accessed using sys.path. The Python interpreter looks for the module in the way described below:
The module is initially looked for in the current working directory. Python then explores every directory in the shell parameter PYTHONPATH if the module cannot be located in the current directory. A list of folders makes up the environment variable known as PYTHONPATH. Python examines the installation-dependent set of folders set up when Python is downloaded if that also fails.
Here is an example to print the path.
Code
# Here, we are importing the sys module
import sys
# Here, we are printing the path using sys.path
print("Path of the sys module in the system is:", sys.path)
Output:Path of the sys module in the system is: [‘/home/pyodide’, ‘/home/pyodide/lib/Python310.zip’, ‘/lib/Python3.10’, ‘/lib/Python3.10/lib-dynload’, ”, ‘/lib/Python3.10/site-packages’]
The dir() Built-in Function
We may use the dir() method to identify names declared within a module.
For instance, we have the following names in the standard module str. To print the names, we will use the dir() method in the following way:
Code
# Here, we are creating a simple Python program to print the directory of a module
print( "List of functions:\n ", dir( str ), end=", " )
Objects are represented by names or identifiers called variables. A namespace is a dictionary containing the names of variables (keys) and the objects that go with them (values).
Both local and global namespace variables can be accessed by a Python statement. When two variables with the same name are local and global, the local variable takes the role of the global variable. There is a separate local namespace for every function. The scoping rule for class methods is the same as for regular functions. Python determines if parameters are local or global based on reasonable predictions. Any variable that is allocated a value in a method is regarded as being local.
Therefore, we must use the global statement before we may provide a value to a global variable inside of a function. Python is informed that Var_Name is a global variable by the line global Var_Name. Python stops looking for the variable inside the local namespace.
We declare the variable Number, for instance, within the global namespace. Since we provide a Number a value inside the function, Python considers a Number to be a local variable. UnboundLocalError will be the outcome if we try to access the value of the local variable without or before declaring it global.
Code
Number = 204
def AddNumber(): # here, we are defining a function with the name Add Number
# Here, we are accessing the global namespace
global Number
Number = Number + 200
print("The number is:", Number)
# here, we are printing the number after performing the addition
AddNumber() # here, we are calling the function
print("The number is:", Number)
In this tutorial, we are discussing Python file handling. Python supports the file-handling process. Till now, we were taking the input from the console and writing it back to the console to interact with the user. Users can easily handle the files, like read and write the files in Python. In another programming language, the file-handling process is lengthy and complicated. But we know Python is an easy programming language. So, like other things, file handling is also effortless and short in Python.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large, and only a limited amount of data can be displayed on the console since the memory is volatile, it is impossible to recover the programmatically generated data again and again.
The file handling plays an important role when the data needs to be stored permanently into the file. A file is a named location on disk to store related information. We can access the stored information (non-volatile) after the program termination.
In Python, files are treated in two modes as text or binary. The file may be in the text or binary format, and each line of a file is ended with the special character like a comma (,) or a newline character. Python executes the code line by line. So, it works in one line and then asks the interpreter to start the new line again. This is a continuous process in Python.
Hence, a file operation can be done in the following order.
Open a file
Read or write – Performing operation
Close the file
Opening a file
A file operation starts with the file opening. At first, open the File then Python will start the operation. File opening is done with the open() function in Python. This function will accepts two arguments, file name and access mode in which the file is accessed. When we use the open() function, that time we must be specified the mode for which the File is opening. The function returns a file object which can be used to perform various operations like reading, writing, etc.
Syntax:
The syntax for opening a file in Python is given below –
The files can be accessed using various modes like read, write, or append. The following are the details about the access mode to open a file.
SN
Access mode
Description
1
r
r means to read. So, it opens a file for read-only operation. The file pointer exists at the beginning. The file is by default open in this mode if no access mode is passed.
2
rb
It opens the file to read-only in binary format. The file pointer exists at the beginning of the file.
3
r+
It opens the file to read and write both. The file pointer exists at the beginning of the file.
4
rb+
It opens the file to read and write both in binary format. The file pointer exists at the beginning of the file.
5
w
It opens the file to write only. It overwrites the file if previously exists or creates a new one if no file exists with the same name. The file pointer exists at the beginning of the file.
6
wb
It opens the file to write only in binary format. It overwrites the file if it exists previously or creates a new one if no file exists. The file pointer exists at the beginning of the file.
7
w+
It opens the file to write and read both. It is different from r+ in the sense that it overwrites the previous file if one exists whereas r+ doesn’t overwrite the previously written file. It creates a new file if no file exists. The file pointer exists at the beginning of the file.
8
wb+
It opens the file to write and read both in binary format. The file pointer exists at the beginning of the file.
9
a
It opens the file in the append mode. The file pointer exists at the end of the previously written file if exists any. It creates a new file if no file exists with the same name.
10
ab
It opens the file in the append mode in binary format. The pointer exists at the end of the previously written file. It creates a new file in binary format if no file exists with the same name.
11
a+
It opens a file to append and read both. The file pointer remains at the end of the file if a file exists. It creates a new file if no file exists with the same name.
12
ab+
It opens a file to append and read both in binary format. The file pointer remains at the end of the file.
Let’s look at the simple example to open a file named “file.txt” (stored in the same directory) in read mode and printing its content on the console.
Program code for read mode:
It is a read operation in Python. We open an existing file with the given code and then read it. The code is given below –
#opens the file file.txt in read mode
fileptr = open(“file.txt”,”r”)
if fileptr:
print(“file is opened successfully”)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -<class ‘_io.TextIOWrapper’> file is opened successfully
In the above code, we have passed filename as a first argument and opened file in read mode as we mentioned r as the second argument. The fileptr holds the file object and if the file is opened successfully, it will execute the print statement
Program code for Write Mode:
It is a write operation in Python. We open an existing file using the given code and then write on it. The code is given below –
file = open('file.txt','w')
file.write("Here we write a command")
file.write("Hello users of JAVATPOINT")
file.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below –
> Hi
ERROR!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Hi' is not defined
The close() Method
The close method used to terminate the program. Once all the operations are done on the file, we must close it through our Python script using the close() method. Any unwritten information gets destroyed once the close() method is called on a file object.
We can perform any operation on the file externally using the file system which is the currently opened in Python; hence it is good practice to close the file once all the operations are done. Earlier use of the close() method can cause the of destroyed some information that you want to write in your File.
The syntax to use the close() method is given below.
Syntax
The syntax for closing a file in Python is given below –
fileobject.close()
Consider the following example.
Program code for Closing Method:
Here we write the program code for the closing method in Python. The code is given below –
# opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("The existing file is opened successfully in Python")
#closes the opened file
fileptr.close()
After closing the file, we cannot perform any operation in the file. The file needs to be properly closed. If any exception occurs while performing some operations in the file then the program terminates without closing the file.
We should use the following method to overcome such type of problem.
The with statement was introduced in python 2.5. The with statement is useful in the case of manipulating the files. It is used in the scenario where a pair of statements is to be executed with a block of code in between.
Syntax:
The syntax of with statement of a file in Python is given below –
with open(<file name>, <access mode>) as <file-pointer>:
#statement suite
The advantage of using with statement is that it provides the guarantee to close the file regardless of how the nested block exits.
It is always suggestible to use the with statement in the case of files because, if the break, return, or exception occurs in the nested block of code then it automatically closes the file, we don’t need to write the close() function. It doesn’t let the file to corrupt.
Program code 1 for with statement:
Here we write the program code for with statement in Python. The code is given below –
with open("file.txt",'r') as f:
content = f.read();
print(content)
Program code 2 for with statement:
Here we write the program code for with statement in Python. The code is given below –
with open("file.txt", "H") as f:
A = f.write("Hello Coders")
Print(A)
Writing the file
To write some text to a file, we need to open the file using the open method and then we can use the write method for writing in this File. If we want to open a file that does not exist in our system, it creates a new one. On the other hand, if the File exists, then erase the past content and add new content to this File. the It is done by the following access modes.
w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.
a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if no file exists.
Program code 1 for Write Method:
Here we write the program code for write method in Python. The code is given below –
# open the file.txt in append mode. Create a new file if no such file exists.
fileptr = open("file2.txt", "w")
# appending the content to the file
fileptr.write(''''''''Python is the modern programming language. It is done any kind of program in shortest way.''')
# closing the opened the file
fileptr.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -File2.txt Python is the modern programming language. It is done any kind of program in shortest way.
We have opened the file in w mode. The file1.txt file doesn’t exist, it created a new file and we have written the content in the file using the write() function
Program code 2 for Write Method:
Here we write the program code for write method in Python. The code is given below –
with open(test1.txt’, ‘w’) as file2:
file2.write(‘Hello coders’)
fil2.write(‘Welcome to javaTpoint’)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Hello coders Welcome to javaTpoint
Program code 3 for Write Method:
Here we write the program code for write method in Python. The code is given below –
#open the file.txt in write mode.
fileptr = open("file2.txt","a")
#overwriting the content of the file
fileptr.write(" Python has an easy syntax and user-friendly interaction.")
#closing the opened file
fileptr.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Python is the modern day language. It makes things so simple. It is the fastest growing language Python has an easy syntax and user-friendly interaction.
Snapshot of the file2.txt
We can see that the content of the file is modified. We have opened the file in a mode and it appended the content in the existing file2.txt.
To read a file using the Python script, the Python provides the read() method. The read() method reads a string from the file. It can read the data in the text as well as a binary format.
Syntax:
The syntax of read() method of a file in Python is given below –
fileobj.read(<count>)
Here, the count is the number of bytes to be read from the file starting from the beginning of the file. If the count is not specified, then it may read the content of the file until the end.
Program code for read() Method:
Here we write the program code for read() method in Python. The code is given below –
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open(“file2.txt”,”r”)
#stores all the data of the file into the variable content
content = fileptr.read(10)
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -<class ‘str’> Python is
In the above code, we have read the content of file2.txt by using the read() function. We have passed count value as ten which means it will read the first ten characters from the file.
If we use the following line, then it will print all content of the file. So, it only prints ‘Python is’. For read the whole file contents, the code is given below –
content = fileptr.read()
print(content)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Python is the modern-day language. It makes things so simple. It is the fastest-growing programming language Python has easy an syntax and user-friendly interaction.
Read file through for loop
We can use read() method when we open the file. Read method is also done through the for loop. We can read the file using for loop. Consider the following example.
Program code 1 for Read File using For Loop:
Here we give an example of read file using for loop. The code is given below –
#open the file.txt in read mode. causes an error if no such file exists.
fileptr = open("file2.txt","r");
#running a for loop
for i in fileptr:
print(i) # i contains each line of the file
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Python is the modern day language. It makes things so simple. Python has easy syntax and user-friendly interaction.
Program code 2 for Read File using For Loop:
Here we give an example of read file using for loop. The code is given below –
A = ["Hello\n", "Coders\n", "JavaTpoint\n"]
f1 = open('myfile.txt', 'w')
f1.writelines(A)
f1.close()
f1 = open('myfile.txt', 'r')
Lines = f1.read()
count = 0
for line in Lines:
count += 1
print("Line{}: {}".format(count, line.strip()))
Output:Line1: H Line2: e Line3: l Line4: l Line5: o Line6: Line7: C Line8: o Line9: d Line10: e Line11: r Line12: s Line13: Line14: J Line15: a Line16: v Line17: a Line18: T Line19: p Line20: o Line21: i Line22: n Line23: t Line24:
Read Lines of the file
Python facilitates to read the file line by line by using a function readline() method. The readline() method reads the lines of the file from the beginning, i.e., if we use the readline() method two times, then we can get the first two lines of the file.
Consider the following example which contains a function readline() that reads the first line of our file “file2.txt” containing three lines. Consider the following example.
Here we give the example of reading the lines using the readline() function in Python. The code is given below –
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readline()
content1 = fileptr.readline()
#prints the content of the file
print(content)
print(content1)
#closes the opened file
fileptr.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Python is the modern day language. It makes things so simple.
We called the readline() function two times that’s why it read two lines from the file.That means, if you called readline() function n times in your program, then it read n number of lines from the file. This is the uses of readline() function in Python. Python provides also the readlines() method which is used for the reading lines. It returns the list of the lines till the end of file(EOF) is reached.
Example 2:
Here we give the example of reading the lines using the readline() function in Python. The code is given below –
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readlines()
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -[‘Python is the modern day language.\n’, ‘It makes things so simple.\n’, ‘Python has easy syntax and user-friendly interaction.’]
Example 3:
Here we give the example of reading the lines using the readline() function in Python. The code is given below –
A = ["Hello\n", "Coders\n", "JavaTpoint\n"]
f1 = open('myfile.txt', 'w')
f1.writelines(A)
f1.close()
f1 = open('myfile.txt', 'r')
Lines = f1.readlines()
count = 0
for line in Lines:
count += 1
print("Line{}: {}".format(count, line.strip()))
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Line1: Hello Line2: Coders Line3: JavaTpoint
Creating a new file
The new file can be created by using one of the following access modes with the function open().The open() function used so many parameters. The syntax of it is given below –
file = open(path_to_file, mode)
x, a and w is the modes of open() function. The uses of these modes are given below –
x: it creates a new file with the specified name. It causes an error a file exists with the same name.
a: It creates a new file with the specified name if no such file exists. It appends the content to the file if the file already exists with the specified name.
w: It creates a new file with the specified name if no such file exists. It overwrites the existing file.
Consider the following example.
Program code1 for Creating a new file:
Here we give an example for creating a new file in Python. For creates a file, we have to used the open() method. The code is given below –
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","x")
print(fileptr)
if fileptr:
print("File created successfully")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -<_io.TextIOWrapper name=’file2.txt’ mode=’x’ encoding=’cp1252′> File created successfully
Program code2 for creating a new file:
Here we give an example for creating a new file in Python. For creates a file, we have to use the open() method. Here we use try block for erase the errors. The code is given below –
try:
with open('file1.txt', 'w') as f:
f.write('Here we create a new file')
except FileNotFoundError:
print("The file is does not exist")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -The file is does not exist
File Pointer positions
Python provides the tell() method which is used to print the byte number at which the file pointer currently exists. The tell() methods is return the position of read or write pointer in this file. The syntax of tell() method is given below –
fileobject.tell()
Program code1 for File Pointer Position:
Here we give an example for how to find file pointer position in Python. Here we use tell() method and it is return byte number. The code is given below –
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#reading the content of the file
content = fileptr.read();
#after the read operation file pointer modifies. tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -The filepointer is at byte : 0 After reading, the filepointer is at: 117
Program code2 for File Pointer Position:
file = open("File2.txt", "r")
print("The pointer position is: ", file.tell())
Here we give another example for how to find file pointer position in Python. Here we also use tell() method, which is return byte number. The code is given below – Here we give another example for how to find file pointer position in Python. Here we also use tell() method, which is return byte number. The code is given below –
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below – The pointer position is: 0
Modifying file pointer position
In real-world applications, sometimes we need to change the file pointer location externally since we may need to read or write the content at various locations.
For this purpose, the Python provides us the seek() method which enables us to modify the file pointer position externally. That means, using seek() method we can easily change the cursor in the file, from where we want to read or write a file.
Syntax:
The syntax for seek() method is given below –
<file-ptr>.seek(offset[, from)
The seek() method accepts two parameters:
offset: It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be moved. If it is set to 0, the beginning of the file is used as the reference position. If it is set to 1, the current position of the file pointer is used as the reference position. If it is set to 2, the end of the file pointer is used as the reference position.
Consider the following example.
Here we give the example of how to modifying the pointer position using seek() method in Python. The code is given below –
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#changing the file pointer location to 10.
fileptr.seek(10);
#tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -The filepointer is at byte : 0 After reading, the filepointer is at: 10
Python OS module:
Renaming the file
The Python os module enables interaction with the operating system. It comes from the Python standard utility module. The os module provides a portable way to use the operating system-dependent functionality in Python. The os module provides the functions that are involved in file processing operations like renaming, deleting, etc. It provides us the rename() method to rename the specified file to a new name. Using the rename() method, we can easily rename the existing File. This method has not any return value. The syntax to use the rename() method is given below.
Syntax:
The syntax of rename method in Python is given below –
rename(current-name, new-name)
The first argument is the current file name and the second argument is the modified name. We can change the file name bypassing these two arguments.
Program code 1 for rename() Method:
Here we give an example of the renaming of the files using rename() method in Python. The current file name is file2.txt, and the new file name is file3.txt. The code is given below –
import os
#rename file2.txt to file3.txt
os.rename("file2.txt","file3.txt")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -The above code renamed current file2.txt to file3.txt
Program code 2 for rename() Method:
Here we give an example of the renaming of the files using rename() method in Python. The current file name is the source, and the new file name is the destination. The code is given below –
import os
def main():
i = 0
path="D:/JavaTpoint/"
for filename in os.listdir(path):
destination = "new" + str(i) + ".png"
source = path + filename
destination = path + destination
os.rename(source, destination)
i += 1
if __name__ == '__main__':
main()
Removing the file
The os module provides the remove() method which is used to remove the specified file.
Syntax:
The syntax of remove method is given below –
remove(file-name)
Program code 1 for remove() method:
import os;
#deleting the file named file3.txt
os.remove("file3.txt")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below – The file named file3.txt is deleted.
Program code 2 for remove() Method:
Here we give an example of removing a file using the remove() method in Python. The file name is file3.txt, which the remove() method deletes. Print the command “This file is not existed” if the File does not exist. The code is given below –
import os
if os.path.exists("file3.txt "):
os.remove("file3.txt ")
else:
print("This file is not existed")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below – This file is not existed
Creating the new directory
The mkdir() method is used to create the directories in the current working directory.It creates dictionary in numeric mode. If the file already presents in the system, then it occurs error, which is known as FileExistsError in Python. The mkdir() method does not return any kind of value. The syntax to create the new directory is given below.
Syntax:
The syntax of mkdir() method in Python is given below –
os.mkdir (path, mode = 0o777, *, dir_fd = None)
Output:
Parameter:
The syntax of mkdir() method in Python is given below –
path – A path like object represent a path either bytes or the strings object.
mode – Mode is represented by integer value, which means mode is created. If mode is not created then the default value will be 0o777. Its use is optional in mkdir() method.
dir_fd – When the specified path is absolute, in that case dir_fd is ignored. Its use is optional in mkdir() method.
Program code 1 for mkdir() Method:
Here we give the example of mkdir() method by which we can create new dictionary in Python. The code is given below –
import os
#creating a new directory with the name new
os.mkdir("new")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Create a new dictionary which is named new
Program code 2 for mkdir() Method:
Here we give the example of mkdir() method by which we can create new dictionary in Python. The code is given below –
import os
path = '/D:/JavaTpoint'
try:
os.mkdir(path)
except OSError as error:
print(error)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below – [Error 20] File exists: ‘/D:/JavaTpoint’
The getcwd() method:
This method returns the current working directory which have absolute value. The getcwd() method returns the string value which represents the working dictionary in Python. In getcwd() method, do not require any parameter.
The syntax to use the getcwd() method is given below.
Syntax
The syntax of getcwd() method in Python is given below –
os.getcwd()
Program code 1 for getcwd() Method:
Here we give the example of getcwd() method by which we can create new dictionary in Python. The code is given below –
import os
os.getcwd()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -‘C:\\Users\\DEVANSH SHARMA’
Program code 2 for getcwd() Method:
Here we give the example of getcwd() method by which we can create new dictionary in Python. The code is given below –
import os
c = os.getcwd()
print("The working directory is:", c)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -The working directory is: C:\\Users\\JavaTpoint
Changing the current working directory
The chdir() method is used to change the current working directory to a specified directory.The chdir() method takes a single argument for the new dictionary path. The chdir() method does not return any kind of value.
Syntax
The syntax of chdir() method is given below –
chdir("new-directory")
Program code 1 for chdir() Method:
Here we give the example of chdir() method by which we can change the current working dictionary into new dictionary in Python. The code is given below –
import os
# Changing current directory with the new directiory
os.chdir("C:\\Users\\DEVANSH SHARMA\\Documents")
#It will display the current working directory
os.getcwd()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -‘C:\\Users\\DEVANSH SHARMA\\Documents’
Program code 2 for chdir() Method:
Here we give another example of chdir() method by which we can change the current working dictionary into new dictionary in Python. The code is given below –
import os
os.chdir(r"C:\Users\JavaTpoint")
print("Currently working directory is changed")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Currently working directory is changed
Deleting directory:
The rmdir() method is used to delete the specified directory. If the directory is not empty then there is occurs OSError. The rmdir() method does not have and kind of return value.
Syntax
os.rmdir(directory name)
Program code 1 for rmdir() Method:
Here we give the example of rmdir() method by which we can delete a dictionary in Python. The code is given below –
import os
#removing the new directory
os.rmdir("directory_name")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -It will remove the specified directory.
Program code 2 for rmdir() Method:
Here we give another example of rmdir() method by which we can delete a dictionary in Python. The code is given below –
import os
directory = "JavaTpoint"
parent = "/D:/User/Documents"
path = os.path.join(parent, directory)
os.rmdir(path)
print("The directory '%s' is successfully removed", %directory)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -The directory ‘JavaTpoint’ is successfully removed
Output:
Here we give the example of rmdir() method by which we can delete a dictionary in Python. Here we use try block for handle the error. The code is given below –
import os
dir = "JavaTpoint"
parent = "/D:/User/Documents"
path = os.path.join(parent, dir)
try:
os.rmdir(path)
print("The directory '%s' is successfully removed", %dir)
except OSError as error:
print(error)
print("The directory '%s' cannot be removed successfully", %dir)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -[Error 30] Permission denied: ‘/D:/User/Documents/JavaTpoint’ The directory ‘JavaTpoint’ cannot be removed successfully
Writing Python output to the files:
In Python, there are the requirements to write the output of a Python script to a file.
The check_call() method of module subprocess is used to execute a Python script and write the output of that script to a file.
The following example contains two python scripts. The script file1.py executes the script file.py and writes its output to the text file output.txt.
Program code:
file1.py
temperatures=[10,-20,-289,100]
def c_to_f(c):
if c< -273.15:
return "That temperature doesn't make sense!"
else:
f=c*9/5+32
return f
for t in temperatures:
print(c_to_f(t))
file.py
import subprocess
with open("output.txt", "wb") as f:
subprocess.check_call(["python", "file.py"], stdout=f)
File Related Methods:
The file object provides the following methods to manipulate the files on various operating systems. Here we discuss the method and their uses in Python.
SN
Method
Description
1
file.close()
It closes the opened file. The file once closed, it can’t be read or write anymore.
2
File.fush()
It flushes the internal buffer.
3
File.fileno()
It returns the file descriptor used by the underlying implementation to request I/O from the OS.
4
File.isatty()
It returns true if the file is connected to a TTY device, otherwise returns false.
5
File.next()
It returns the next line from the file.
6
File.read([size])
It reads the file for the specified size.
7
File.readline([size])
It reads one line from the file and places the file pointer to the beginning of the new line.
8
File.readlines([sizehint])
It returns a list containing all the lines of the file. It reads the file until the EOF occurs using readline() function.
9
File.seek(offset[,from)
It modifies the position of the file pointer to a specified offset with the specified reference.
10
File.tell()
It returns the current position of the file pointer within the file.
11
File.truncate([size])
It truncates the file to the optional specified size.
12
File.write(str)
It writes the specified string to a file
13
File.writelines(seq)
It writes a sequence of the strings to a file.
Conclusion:
In this tutorial, we briefly discussed the Python file handling. Users can easily handle the files, like read and write the files in Python. Here we discuss various methods in Python by which we can easily read, write, delete, or rename a file. We also give the program code of these methods for better understanding.
This tutorial will study anonymous, commonly called lambda functions in Python. A lambda function can take n number of arguments at a time. But it returns only one argument at a time. We will understand what they are, how to execute them, and their syntax.
What are Lambda Functions in Python?
Lambda Functions in Python are anonymous functions, implying they don’t have a name. The def keyword is needed to create a typical function in Python, as we already know. We can also use the lambda keyword in Python to define an unnamed function.
Syntax
The syntax of the Lambda Function is given below –
lambda arguments: expression
This function accepts any count of inputs but only evaluates and returns one expression. That means it takes many inputs but returns only one output.
Lambda functions can be used whenever function arguments are necessary. In addition to other forms of formulations in functions, it has a variety of applications in certain coding domains. It’s important to remember that according to syntax, lambda functions are limited to a single statement.
Example
Here we share some examples of lambda functions in Python for learning purposes. Program Code 1:
Now we gave an example of a lambda function that adds 4 to the input number is shown below.
# Code to demonstrate how we can use a lambda function for adding 4 numbers
add = lambda num: num + 4
print( add(6) )
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -10
Here we explain the above code. The lambda function is “lambda num: num+4” in the given programme. The parameter is num, and the computed and returned equation is num * 4.
There is no label for this function. It generates a function object associated with the “add” identifier. We can now refer to it as a standard function. The lambda statement, “lambda num: num+4”, is written using the add function, and the code is given below: Program Code 2:
Now we gave an example of a lambda function that adds 4 to the input number using the add function. The code is shown below –
def add( num ):
return num + 4
print( add(6) )
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -10
Program Code 3:
Now we gave an example of a lambda function that multiply 2 numbers and return one result. The code is shown below –
a = lambda x, y : (x * y)
print(a(4, 5))
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -20
Program Code 4:
Now we gave another example of a lambda function that adds 2 numbers and return one result. The code is shown below –
a = lambda x, y, z : (x + y + z)
print(a(4, 5, 5))
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -14
What’s the Distinction Between Lambda and Def Functions?
Let’s glance at this instance to see how a conventional def defined function differs from a function defined using the lambda keyword. This program calculates the reciprocal of a given number:
# Python code to show the reciprocal of the given number to highlight the difference between def() and lambda().
def reciprocal( num ):
return 1 / num
lambda_reciprocal = lambda num: 1 / num
# using the function defined by def keyword
print( "Def keyword: ", reciprocal(6) )
# using the function defined by lambda keyword
print( "Lambda keyword: ", lambda_reciprocal(6) )
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -Def keyword: 0.16666666666666666 Lambda keyword: 0.16666666666666666
Explanation:
The reciprocal() and lambda_reciprocal() functions act similarly and as expected in the preceding scenario. Let’s take a closer look at the sample above:
Both of these yield the reciprocal of a given number without employing Lambda. However, we wanted to declare a function with the name reciprocal and send a number to it while executing def. We were also required to use the return keyword to provide the output from wherever the function was invoked after being executed.
Using Lambda: Instead of a “return” statement, Lambda definitions always include a statement given at output. The beauty of lambda functions is their convenience. We need not allocate a lambda expression to a variable because we can put it at any place a function is requested.
Using Lambda Function with filter()
The filter() method accepts two arguments in Python: a function and an iterable such as a list.
The function is called for every item of the list, and a new iterable or list is returned that holds just those elements that returned True when supplied to the function.
Here’s a simple illustration of using the filter() method to return only odd numbers from a list.
Program Code:
Here we give an example of lambda function with filter() in Python. The code is given below –
# This code used to filter the odd numbers from the given list
list_ = [35, 12, 69, 55, 75, 14, 73]
odd_list = list(filter( lambda num: (num % 2 != 0) , list_ ))
print('The list of odd number is:',odd_list)
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -The list of odd number is: [35, 69, 55, 75, 73]
Using Lambda Function with map()
A method and a list are passed to Python’s map() function.
The function is executed for all of the elements within the list, and a new list is produced with elements generated by the given function for every item.
The map() method is used to square all the entries in a list in this example.
Program Code:
Here we give an example of lambda function with map() in Python. Then code is given below –
#Code to calculate the square of each number of a list using the map() function
numbers_list = [2, 4, 5, 1, 3, 7, 8, 9, 10]
squared_list = list(map( lambda num: num ** 2 , numbers_list ))
print( 'Square of each number in the given list:' ,squared_list )
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -Square of each number in the given list: [4, 16, 25, 1, 9, 49, 64, 81, 100]
Using Lambda Function with List Comprehension
In this instance, we will apply the lambda function combined with list comprehension and the lambda keyword with a for loop. Using the Lambda Function with List Comprehension, we can print the square value from 0 to 10. For printing the square value from 0 to 10, we create a loop range from 0 to 11.
Program Code:
Here we give an example of lambda function with List Comprehension in Python. Then code is given below –
#Code to calculate square of each number of lists using list comprehension
squares = [lambda num = num: num ** 2 for num in range(0, 11)]
for square in squares:
print('The square value of all numbers from 0 to 10:',square(), end = " ")
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -The square value of all numbers from 0 to 10: 0 1 4 9 16 25 36 49 64 81 100
Using Lambda Function with if-else
We will use the lambda function with the if-else block. In the program code below, we check which number is greater than the given two numbers using the if-else block.
Program Code:
Here we give an example of a lambda function with an if-else block in Python. The code is given below –
# Code to use lambda function with if-else
Minimum = lambda x, y : x if (x < y) else y
print('The greater number is:', Minimum( 35, 74 ))
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -The greater number is: 35
Using Lambda with Multiple Statements
Multiple expressions are not allowed in lambda functions, but we can construct 2 lambda functions or more and afterward call the second lambda expression as an argument to the first. We are sorting every sub-list from the given list in the below program. Let us use lambda to discover the third largest number from every sub-list.
Program Code:
Here we give an example of lambda function with Multiple Statements in Python. The code is given below –
# Code to print the third largest number of the given list using the lambda function
my_List = [ [3, 5, 8, 6], [23, 54, 12, 87], [1, 2, 4, 12, 5] ]
# sorting every sublist of the above list
sort_List = lambda num : ( sorted(n) for n in num )
# Getting the third largest number of the sublist
third_Largest = lambda num, func : [ l[ len(l) - 2] for l in func(num)]
result = third_Largest( my_List, sort_List)
print('The third largest number from every sub list is:', result )
Output:
Now we compile the above code, in python and after successful compilation, we run it. Then the output is given below -The third largest number from every sub list is: [6, 54, 5]
Conclusion:
So, in this, we discuss the Lambda function in Python. A lambda function can take n number of arguments at a time. But it returns only one argument at a time. Here we discuss some lambda functions with the program code in Python, and we also share some examples of them. Here we discuss the Lambda function with the list, map, filter, multiple statements, if-else, and some basic programs of lambda function in Python.
A collection of related assertions that carry out a mathematical, analytical, or evaluative operation is known as a function. An assortment of proclamations called Python Capabilities returns the specific errand. Python functions are necessary for intermediate-level programming and are easy to define. Function names meet the same standards as variable names do. The objective is to define a function and group-specific frequently performed actions. Instead of repeatedly creating the same code block for various input variables, we can call the function and reuse the code it contains with different variables.
Client-characterized and worked-in capabilities are the two primary classes of capabilities in Python. It aids in maintaining the program’s uniqueness, conciseness, and structure.
Advantages of Python Functions
Pause We can stop a program from repeatedly using the same code block by including functions.
Once defined, Python functions can be called multiple times and from any location in a program.
Our Python program can be broken up into numerous, easy-to-follow functions if it is significant.
The ability to return as many outputs as we want using a variety of arguments is one of Python’s most significant achievements.
However, Python programs have always incurred overhead when calling functions.
However, calling functions has always been overhead in a Python program.
Syntax
# An example Python Function
def function_name( parameters ):
# code block
The accompanying components make up to characterize a capability, as seen previously.
The start of a capability header is shown by a catchphrase called def.
function_name is the function’s name, which we can use to distinguish it from other functions. We will utilize this name to call the capability later in the program. Name functions in Python must adhere to the same guidelines as naming variables.
Using parameters, we provide the defined function with arguments. Notwithstanding, they are discretionary.
A colon (:) marks the function header’s end.
We can utilize a documentation string called docstring in the short structure to make sense of the reason for the capability.
Several valid Python statements make up the function’s body. The entire code block’s indentation depth-typically four spaces-must be the same.
A return expression can get a value from a defined function.
Illustration of a User-Defined Function
We will define a function that returns the argument number’s square when called.
# Example Python Code for User-Defined function
def square( num ):
"""
This function computes the square of the number.
"""
return num**2
object_ = square(6)
print( "The square of the given number is: ", object_ )
Output:The square of the given number is: 36
Calling a Function
Calling a Function To define a function, use the def keyword to give it a name, specify the arguments it must receive, and organize the code block.
When the fundamental framework for a function is finished, we can call it from anywhere in the program. An illustration of how to use the a_function function can be found below.
# Example Python Code for calling a function
# Defining a function
def a_function( string ):
"This prints the value of length of string"
return len(string)
# Calling the function we defined
print( "Length of the string Functions is: ", a_function( "Functions" ) )
print( "Length of the string Python is: ", a_function( "Python" ) )
Output:Length of the string Functions is: 9 Length of the string Python is: 6
Pass by Reference vs. Pass by Value
In the Python programming language, all parameters are passed by reference. It shows that if we modify the worth of contention within a capability, the calling capability will similarly mirror the change. For instance,
Code
# Example Python Code for Pass by Reference vs. Value
# defining the function
def square( item_list ):
'''''''This function will find the square of items in the list'''
squares = [ ]
for l in item_list:
squares.append( l**2 )
return squares
# calling the defined function
my_list = [17, 52, 8];
my_result = square( my_list )
print( "Squares of the list are: ", my_result )
Output:Squares of the list are: [289, 2704, 64]
Function Arguments
The following are the types of arguments that we can use to call a function:
A default contention is a boundary that takes as information a default esteem, assuming that no worth is provided for the contention when the capability is called. The following example demonstrates default arguments.
Code
# Python code to demonstrate the use of default arguments
# defining a function
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling the function and passing only one argument
print( "Passing only one argument" )
function(30)
# Now giving two arguments to the function
print( "Passing two arguments" )
function(50,30)
Output:Passing only one argument number 1 is: 30 number 2 is: 20 Passing two arguments number 1 is: 50 number 2 is: 30
2) Keyword Arguments
Keyword arguments are linked to the arguments of a called function. While summoning a capability with watchword contentions, the client might tell whose boundary esteem it is by looking at the boundary name.
We can eliminate or orchestrate specific contentions in an alternate request since the Python translator will interface the furnished watchwords to connect the qualities with its boundaries. One more method for utilizing watchwords to summon the capability() strategy is as per the following:
Code
# Python code to demonstrate the use of keyword arguments
# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling function and passing arguments without using keyword
print( "Without using keyword" )
function( 50, 30)
# Calling function and passing arguments using keyword
print( "With using keyword" )
function( n2 = 50, n1 = 30)
Output:Without using keyword number 1 is: 50 number 2 is: 30 With using keyword number 1 is: 30 number 2 is: 50
3) Required Arguments
Required arguments are those supplied to a function during its call in a predetermined positional sequence. The number of arguments required in the method call must be the same as those provided in the function’s definition.
We should send two contentions to the capability() all put together; it will return a language structure blunder, as seen beneath.
Code
# Python code to demonstrate the use of default arguments
# Defining a function
def function( n1, n2 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling function and passing two arguments out of order, we need num1 to be 20 and num2 to be 30
print( "Passing out of order arguments" )
function( 30, 20 )
# Calling function and passing only one argument
print( "Passing only one argument" )
try:
function( 30 )
except:
print( "Function needs two positional arguments" )
Output:Passing out of order arguments number 1 is: 30 number 2 is: 20 Passing only one argument Function needs two positional arguments
4) Variable-Length Arguments
We can involve unique characters in Python capabilities to pass many contentions. However, we need a capability. This can be accomplished with one of two types of characters:
“args” and “kwargs” refer to arguments not based on keywords.
To help you understand arguments of variable length, here’s an example.
Code
# Python code to demonstrate the use of variable-length arguments
# Defining a function
def function( *args_list ):
ans = []
for l in args_list:
ans.append( l.upper() )
return ans
# Passing args arguments
object = function('Python', 'Functions', 'tutorial')
print( object )
# defining a function
def function( **kargs_list ):
ans = []
for key, value in kargs_list.items():
ans.append([key, value])
return ans
# Paasing kwargs arguments
object = function(First = "Python", Second = "Functions", Third = "Tutorial")
print(object)
When a defined function is called, a return statement is written to exit the function and return the calculated value.
Syntax:
return < expression to be returned as output >
The return statement can be an argument, a statement, or a value, and it is provided as output when a particular job or function is finished. A declared function will return an empty string if no return statement is written.
A return statement in Python functions is depicted in the following example.
Code
# Python code to demonstrate the use of return statements
# Defining a function with return statement
def square( num ):
return num**2
# Calling function and passing arguments.
print( "With return statement" )
print( square( 52 ) )
# Defining a function without return statement
def square( num ):
num**2
# Calling function and passing arguments.
print( "Without return statement" )
print( square( 52 ) )
Output:With return statement 2704 Without return statement None
The Anonymous Functions
Since we do not use the def keyword to declare these kinds of Python functions, they are unknown. The lambda keyword can define anonymous, short, single-output functions.
Arguments can be accepted in any number by lambda expressions; However, the function only produces a single value from them. They cannot contain multiple instructions or expressions. Since lambda needs articulation, a mysterious capability can’t be straightforwardly called to print.
Lambda functions can only refer to variables in their argument list and the global domain name because they contain their distinct local domain.
In contrast to inline expressions in C and C++, which pass function stack allocations at execution for efficiency reasons, lambda expressions appear to be one-line representations of functions.
Syntax
Lambda functions have exactly one line in their syntax:
Below is an illustration of how to use the lambda function:
Code
# Python code to demonstrate ananymous functions
# Defining a function
lambda_ = lambda argument1, argument2: argument1 + argument2;
# Calling the function and passing values
print( "Value of the function is : ", lambda_( 20, 30 ) )
print( "Value of the function is : ", lambda_( 40, 50 ) )
Output:Value of the function is : 50 Value of the function is : 90
Scope and Lifetime of Variables
A variable’s scope refers to the program’s domain wherever it is declared. A capability’s contentions and factors are not external to the characterized capability. They only have a local domain as a result.
The length of time a variable remains in RAM is its lifespan. The lifespan of a function is the same as the lifespan of its internal variables. When we exit the function, they are taken away from us. As a result, the value of a variable in a function does not persist from previous executions.
An easy illustration of a function’s scope for a variable can be found here.
Code
# Python code to demonstrate scope and lifetime of variables
#defining a function to print a number.
def number( ):
num = 50
print( "Value of num inside the function: ", num)
num = 10
number()
print( "Value of num outside the function:", num)
Output:Value of num inside the function: 50 Value of num outside the function: 10
Here, we can see that the initial value of num is 10. Even though the function number() changed the value of num to 50, the value of num outside of the function remained unchanged.
This is because the capability’s interior variable num is not quite the same as the outer variable (nearby to the capability). Despite having a similar variable name, they are separate factors with discrete extensions.
Factors past the capability are available inside the capability. The impact of these variables is global. We can retrieve their values within the function, but we cannot alter or change them. The value of a variable can be changed outside of the function if it is declared global with the keyword global.
Python Capability inside Another Capability
Capabilities are viewed as top-of-the-line objects in Python. First-class objects are treated the same everywhere they are used in a programming language. They can be stored in built-in data structures, used as arguments, and in conditional expressions. If a programming language treats functions like first-class objects, it is considered to implement first-class functions. Python lends its support to the concept of First-Class functions.
A function defined within another is called an “inner” or “nested” function. The parameters of the outer scope are accessible to inner functions. Internal capabilities are developed to cover them from the progressions outside the capability. Numerous designers see this interaction as an embodiment.
Code
# Python code to show how to access variables of a nested functions
# defining a nested function
def word():
string = 'Python functions tutorial'
x = 5
def number():
print( string )
print( x )
number()
word()
Dictionaries are a useful data structure for storing data in Python because they are capable of imitating real-world data arrangements where a certain value exists for a given key.
The data is stored as key-value pairs using a Python dictionary.
This data structure is mutable
The components of dictionary were made using keys and values.
Keys must only have one component.
Values can be of any type, including integer, list, and tuple.
A dictionary is, in other words, a group of key-value pairs, where the values can be any Python object. The keys, in contrast, are immutable Python objects, such as strings, tuples, or numbers. Dictionary entries are ordered as of Python version 3.7. In Python 3.6 and before, dictionaries are generally unordered.
Creating the Dictionary
Curly brackets are the simplest way to generate a Python dictionary, although there are other approaches as well. With many key-value pairs surrounded in curly brackets and a colon separating each key from its value, the dictionary can be built. (:). The following provides the syntax for defining the dictionary.
Syntax:
Dict = {"Name": "Gayle", "Age": 25}
In the above dictionary Dict, The keys Name and Age are the strings which comes under the category of an immutable object.
Let’s see an example to create a dictionary and print its content.
Python provides the built-in function dict() method which is also used to create the dictionary.
The empty curly braces {} is used to create empty dictionary.
Code
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(4, 'Rinku'), (2, Singh)])
print("\nDictionary with each item as a pair: ")
print(Dict)
OutputEmpty Dictionary: {} Create Dictionary by using dict(): {1: ‘Hcl’, 2: ‘WIPRO’, 3: ‘Facebook’} Dictionary with each item as a pair: {4: ‘Rinku’, 2: ‘Singh’}
Accessing the dictionary values
To access data contained in lists and tuples, indexing has been studied. The keys of the dictionary can be used to obtain the values because they are unique from one another. The following method can be used to access dictionary values.
Outputee[“Company”]) Output <class ‘dict’> printing Employee data …. Name : Dev Age : 20 Salary : 45000 Company : WIPRO
Python provides us with an alternative to use the get() method to access the dictionary values. It would give the same result as given by the indexing.
Adding Dictionary Values
The dictionary is a mutable data type, and utilising the right keys allows you to change its values. Dict[key] = value and the value can both be modified. An existing value can also be updated using the update() method.
Note: The value is updated if the key-value pair is already present in the dictionary. Otherwise, the dictionary’s newly added keys.
Let’s see an example to update the dictionary values.
Example – 1:
Code
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements to dictionary one at a time
Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[3] = 'JavaTpoint'
print("\nUpdated key value: ")
print(Dict)
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)
Output<class ‘dict’> printing Employee data …. Employee = {“Name”: “Dev”, “Age”: 20, “salary”:45000,”Company”:”WIPRO”} Enter the details of the new employee…. Name: Sunny Age: 38 Salary: 39000 Company:Hcl printing the new data {‘Name’: ‘Sunny’, ‘Age’: 38, ‘salary’: 39000, ‘Company’: ‘Hcl’}
Deleting Elements using del Keyword
The items of the dictionary can be deleted by using the del keyword as given below.
Code
Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Output<class ‘dict’> printing Employee data …. {‘Name’: ‘David’, ‘Age’: 30, ‘salary’: 55000, ‘Company’: ‘WIPRO’} Deleting some of the employee data printing the modified information {‘Age’: 30, ‘salary’: 55000} Deleting the dictionary: Employee Lets try to print it again NameError: name ‘Employee’ is not defined.
The last print statement in the above code, it raised an error because we tried to print the Employee dictionary that already deleted.
Deleting Elements using pop() Method
A dictionary is a group of key-value pairs in Python. You can retrieve, insert, and remove items using this unordered, mutable data type by using their keys. The pop() method is one of the ways to get rid of elements from a dictionary. In this post, we’ll talk about how to remove items from a Python dictionary using the pop() method.
The value connected to a specific key in a dictionary is removed using the pop() method, which then returns the value. The key of the element to be removed is the only argument needed. The pop() method can be used in the following ways:
Code
# Creating a Dictionary
Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}
# Deleting a key
# using pop() method
pop_key = Dict1.pop(2)
print(Dict1)
Output{1: ‘JavaTpoint’, 3: ‘Website’}
Additionally, Python offers built-in functions popitem() and clear() for removing dictionary items. In contrast to the clear() method, which removes all of the elements from the entire dictionary, popitem() removes any element from a dictionary.
Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example 1
Code
# for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee:
print(x)
OutputName Age salary Company
Example 2
Code
#for loop to print all the values of the dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"} for x in Employee:
print(Employee[x])
OutputJohn 29 25000 WIPRO
Example – 3
Code
#for loop to print the values of the dictionary by using values() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee.values():
print(x)
OutputJohn 29 25000 WIPRO
Example 4
Code
#for loop to print the items of the dictionary by using items() method
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee.items():
print(x)
1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value for a single key, then the value which is last assigned is considered as the value of the key.
Consider the following example.
Code
Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO","Name":
"John"}
for x,y in Employee.items():
print(x,y)
OutputName John Age 29 Salary 25000 Company WIPRO
2. The key cannot belong to any mutable object in Python. Numbers, strings, or tuples can be used as the key, however mutable objects like lists cannot be used as the key in a dictionary.
Consider the following example.
Code
Employee = {"Name": "John", "Age": 29, "salary":26000,"Company":"WIPRO",[100,201,301]:"Department ID"}
for x,y in Employee.items():
print(x,y)
A function is a method that can be used on a construct to yield a value. Additionally, the construct is unaltered. A few of the Python methods can be combined with a Python dictionary.
The built-in Python dictionary methods are listed below, along with a brief description.
len()
The dictionary’s length is returned via the len() function in Python. The string is lengthened by one for each key-value pair.
Like how it does with lists and tuples, the any() method returns True indeed if one dictionary key does have a Boolean expression that evaluates to True.
Like it does with lists and tuples, the sorted() method returns an ordered series of the dictionary’s keys. The ascending sorting has no effect on the original Python dictionary.
A Python set is the collection of the unordered items. Each element in the set must be unique, immutable, and the sets remove the duplicate elements. Sets are mutable which means we can modify it after its creation.
Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we cannot directly access any element of the set by the index. However, we can print them all together, or we can get the list of elements by looping through the set.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly braces {}. Python also provides the set() method, which can be used to create the set by the passed sequence.
Example 1: Using curly braces
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Output:{‘Friday’, ‘Tuesday’, ‘Monday’, ‘Saturday’, ‘Thursday’, ‘Sunday’, ‘Wednesday’} <class ‘set’> looping through the set elements … Friday Tuesday Monday Saturday Thursday Sunday Wednesday
Example 2: Using set() method
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Output:{‘Friday’, ‘Wednesday’, ‘Thursday’, ‘Saturday’, ‘Monday’, ‘Tuesday’, ‘Sunday’} <class ‘set’> looping through the set elements … Friday Wednesday Thursday Saturday Monday Tuesday Sunday
It can contain any type of element such as integer, float, tuple etc. But mutable elements (list, dictionary, set) can’t be a member of set. Consider the following example.
# Creating a set which have immutable elements
set1 = {1,2,3, "JavaTpoint", 20.5, 14}
print(type(set1))
#Creating a set which have mutable element
set2 = {1,2,3,["Javatpoint",4]}
print(type(set2))
Output:<class ‘set’> Traceback (most recent call last) <ipython-input-5-9605bb6fbc68> in <module> 4 5 #Creating a set which holds mutable elements —-> 6 set2 = {1,2,3,[“Javatpoint”,4]} 7 print(type(set2)) TypeError: unhashable type: ‘list’
In the above code, we have created two sets, the set set1 have immutable elements and set2 have one mutable element as a list. While checking the type of set2, it raised an error, which means set can contain only immutable elements.
Creating an empty set is a bit different because empty curly {} braces are also used to create a dictionary as well. So Python provides the set() method used without an argument to create an empty set.
# Empty curly braces will create dictionary
set3 = {}
print(type(set3))
# Empty set using set() function
set4 = set()
print(type(set4))
Output:<class ‘dict’> <class ‘set’>
Let’s see what happened if we provide the duplicate element to the set.
set5 = {1,2,4,4,5,8,9,9,10}
print("Return set with unique elements:",set5)
Output:Return set with unique elements: {1, 2, 4, 5, 8, 9, 10}
In the above code, we can see that set5 consisted of multiple duplicate elements when we printed it remove the duplicity from the set.
Adding items to the set
Python provides the add() method and update() method which can be used to add some particular item to the set. The add() method is used to add a single element whereas the update() method is used to add multiple elements to the set. Consider the following example.
Example: 1 – Using add() method
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
Output:printing the original set … {‘February’, ‘May’, ‘April’, ‘March’, ‘June’, ‘January’} Adding other months to the set… Printing the modified set… {‘February’, ‘July’, ‘May’, ‘April’, ‘March’, ‘August’, ‘June’, ‘January’} looping through the set elements … February July May April March August June January
To add more than one item in the set, Python provides the update() method. It accepts iterable as an argument.
Consider the following example.
Example – 2 Using update() function
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"]);
print("\nprinting the modified set ... ")
print(Months);
Output:printing the original set … {‘January’, ‘February’, ‘April’, ‘May’, ‘June’, ‘March’} updating the original set … printing the modified set … {‘January’, ‘February’, ‘April’, ‘August’, ‘October’, ‘May’, ‘June’, ‘July’, ‘September’, ‘March’}
Removing items from the set
Python provides the discard() method and remove() method which can be used to remove the items from the set. The difference between these function, using discard() function if the item does not exist in the set then the set remain unchanged whereas remove() method will through an error.
Consider the following example.
Example-1 Using discard() method
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.discard("January");
months.discard("May");
print("\nPrinting the modified set...");
print(months)
print("\nlooping through the set elements ... ")
for i in months:
print(i)
Output:printing the original set … {‘February’, ‘January’, ‘March’, ‘April’, ‘June’, ‘May’} Removing some months from the set… Printing the modified set… {‘February’, ‘March’, ‘April’, ‘June’} looping through the set elements … February March April June
Python provides also the remove() method to remove the item from the set. Consider the following example to remove the items using remove() method.
Example-2 Using remove() function
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.remove("January");
months.remove("May");
print("\nPrinting the modified set...");
print(months)
Output:printing the original set … {‘February’, ‘June’, ‘April’, ‘May’, ‘January’, ‘March’} Removing some months from the set… Printing the modified set… {‘February’, ‘June’, ‘April’, ‘March’}
We can also use the pop() method to remove the item. Generally, the pop() method will always remove the last item but the set is unordered, we can’t determine which element will be popped from set.
Consider the following example to remove the item from the set using pop() method.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...");
Months.pop();
Months.pop();
print("\nPrinting the modified set...");
print(Months)
Output:printing the original set … {‘June’, ‘January’, ‘May’, ‘April’, ‘February’, ‘March’} Removing some months from the set… Printing the modified set… {‘May’, ‘April’, ‘February’, ‘March’}
In the above code, the last element of the Month set is March but the pop() method removed the June and January because the set is unordered and the pop() method could not determine the last element of the set.
Python provides the clear() method to remove all the items from the set.
Consider the following example.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving all the items from the set...");
Months.clear()
print("\nPrinting the modified set...")
print(Months)
Output:printing the original set … {‘January’, ‘May’, ‘June’, ‘April’, ‘March’, ‘February’} Removing all the items from the set… Printing the modified set… set()
Difference between discard() and remove()
Despite the fact that discard() and remove() method both perform the same task, There is one main difference between discard() and remove().
If the key to be deleted from the set using discard() doesn’t exist in the set, the Python will not give the error. The program maintains its control flow.
On the other hand, if the item to be deleted from the set using remove() doesn’t exist in the set, the Python will raise an error.
Consider the following example.
Example-
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving items through discard() method...");
Months.discard("Feb"); #will not give an error although the key feb is not available in the set
print("\nprinting the modified set...")
print(Months)
print("\nRemoving items through remove() method...");
Months.remove("Jan") #will give an error as the key jan is not available in the set.
print("\nPrinting the modified set...")
print(Months)
Output:printing the original set … {‘March’, ‘January’, ‘April’, ‘June’, ‘February’, ‘May’} Removing items through discard() method… printing the modified set… {‘March’, ‘January’, ‘April’, ‘June’, ‘February’, ‘May’} Removing items through remove() method… Traceback (most recent call last): File “set.py”, line 9, in Months.remove(“Jan”) KeyError: ‘Jan’
Python Set Operations
Set can be performed mathematical operation such as union, intersection, difference, and symmetric difference. Python provides the facility to carry out these operations with operators or methods. We describe these operations as follows.
Union of two Sets
To combine two or more sets into one set in Python, use the union() function. All of the distinctive characteristics from each combined set are present in the final set. As parameters, one or more sets may be passed to the union() function. The function returns a copy of the set supplied as the lone parameter if there is just one set. The method returns a new set containing all the different items from all the arguments if more than one set is supplied as an argument.
Consider the following example to calculate the union of two sets.
Example 1: using union | operator
Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1|Days2) #printing the union of the sets
Now, we can also make the union of more than two sets using the union() function, for example:
Program:
# Create three sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
# Find the common elements between the three sets
common_elements = set1.union(set2, set3)
# Print the common elements
print(common_elements)
Output:{1, 2, 3, 4, 5}
The intersection of two sets
To discover what is common between two or more sets in Python, apply the intersection() function. Only the items in all sets being compared are included in the final set. One or more sets can also be used as the intersection() function parameters. The function returns a copy of the set supplied as the lone parameter if there is just one set. The method returns a new set that only contains the elements in all the compared sets if multiple sets are supplied as arguments.
The intersection of two sets can be performed by the and & operator or the intersection() function. The intersection of the two sets is given as the set of the elements that common in both sets.
Consider the following example.
Example 1: Using & operator
Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday","Tuesday","Sunday", "Friday"}
print(Days1&Days2) #prints the intersection of the two sets
Output:{‘Monday’, ‘Tuesday’}
Example 2: Using intersection() method
set1 = {"Devansh","John", "David", "Martin"}
set2 = {"Steve", "Milan", "David", "Martin"}
print(set1.intersection(set2)) #prints the intersection of the two sets
Output:{‘Martin’, ‘David’}
Example 3:
set1 = {1,2,3,4,5,6,7}
set2 = {1,2,20,32,5,9}
set3 = set1.intersection(set2)
print(set3)
Output:{1,2,5}
Similarly, as the same as union function, we can perform the intersection of more than two sets at a time,
For Example:
Program
# Create three sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
# Find the common elements between the three sets
common_elements = set1.intersection(set2, set3)
# Print the common elements
print(common_elements)
Output:{3}
The intersection_update() method
The intersection_update() method removes the items from the original set that are not present in both the sets (all the sets if more than one are specified).
The intersection_update() method is different from the intersection() method since it modifies the original set by removing the unwanted items, on the other hand, the intersection() method returns a new set.
Consider the following example.
a = {"Devansh", "bob", "castle"}
b = {"castle", "dude", "emyway"}
c = {"fuson", "gaurav", "castle"}
a.intersection_update(b, c)
print(a)
Output:{‘castle’}
Difference between the two sets
The difference of two sets can be calculated by using the subtraction (-) operator or intersection() method. Suppose there are two sets A and B, and the difference is A-B that denotes the resulting set will be obtained that element of A, which is not present in the set B.
Consider the following example.
Example 1 : Using subtraction ( – ) operator
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}
Output:{‘Thursday’, ‘Wednesday’}
Example 2 : Using difference() method
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2
Output:{‘Thursday’, ‘Wednesday’}
Symmetric Difference of two sets
In Python, the symmetric Difference between set1 and set2 is the set of elements present in one set or the other but not in both sets. In other words, the set of elements is in set1 or set2 but not in their intersection.
The Symmetric Difference of two sets can be computed using Python’s symmetric_difference() method. This method returns a new set containing all the elements in either but not in both. Consider the following example:
Example – 1: Using ^ operator
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a^b
print(c)
Output:{3, 4, 5, 6, 8, 9, 10}
Example – 2: Using symmetric_difference() method
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a.symmetric_difference(b)
print(c)
Output:{3, 4, 5, 6, 8, 9, 10}
Set comparisons
In Python, you can compare sets to check if they are equal, if one set is a subset or superset of another, or if two sets have elements in common.
Here are the set comparison operators available in Python:
==: checks if two sets have the same elements, regardless of their order.
!=: checks if two sets are not equal.
<: checks if the left set is a proper subset of the right set (i.e., all elements in the left set are also in the right set, but the right set has additional elements).
<=: checks if the left set is a subset of the right set (i.e., all elements in the left set are also in the right set).
>: checks if the left set is a proper superset of the right set (i.e., all elements in the right set are also in the left set, but the left set has additional elements).
>=: checks if the left set is a superset of the right set (i.e., all elements in the right set are also in the left).
Consider the following example.
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}
#Days1 is the superset of Days2 hence it will print true.
print (Days1>Days2)
#prints false since Days1 is not the subset of Days2
print (Days1<Days2)
#prints false since Days2 and Days3 are not equivalent
print (Days2 == Days3)
Output:True False False
FrozenSets
In Python, a frozen set is an immutable version of the built-in set data type. It is similar to a set, but its contents cannot be changed once a frozen set is created.
Frozen set objects are unordered collections of unique elements, just like sets. They can be used the same way as sets, except they cannot be modified. Because they are immutable, frozen set objects can be used as elements of other sets or dictionary keys, while standard sets cannot.
One of the main advantages of using frozen set objects is that they are hashable, meaning they can be used as keys in dictionaries or as elements of other sets. Their contents cannot change, so their hash values remain constant. Standard sets are not hashable because they can be modified, so their hash values can change.
Frozen set objects support many of the assets of the same operation, such as union, intersection, Difference, and symmetric Difference. They also support operations that do not modify the frozen set, such as len(), min(), max(), and in.
Consider the following example to create the frozen set.
Frozenset = frozenset([1,2,3,4,5])
print(type(Frozenset))
print("\nprinting the content of frozen set...")
for i in Frozenset:
print(i);
Frozenset.add(6) #gives an error since we cannot change the content of Frozenset after creation
Output:<class ‘frozenset’> printing the content of frozen set… 1 2 3 4 5 Traceback (most recent call last): File “set.py”, line 6, in <module> Frozenset.add(6) #gives an error since we can change the content of Frozenset after creation AttributeError: ‘frozenset’ object has no attribute ‘add’
Frozenset for the dictionary
If we pass the dictionary as the sequence inside the frozenset() method, it will take only the keys from the dictionary and returns a frozenset that contains the key of the dictionary as its elements.
Consider the following example.
Dictionary = {"Name":"John", "Country":"USA", "ID":101}
print(type(Dictionary))
Frozenset = frozenset(Dictionary); #Frozenset will contain the keys of the dictionary
print(type(Frozenset))
for i in Frozenset:
print(i)
Output:<class ‘dict’> <class ‘frozenset’> Name Country ID
Set Programming Example
Example – 1: Write a program to remove the given number from the set.
my_set = {1,2,3,4,5,6,12,24}
n = int(input("Enter the number you want to remove"))
my_set.discard(n)
print("After Removing:",my_set)
Output:Enter the number you want to remove:12 After Removing: {1, 2, 3, 4, 5, 6, 24}
Example – 2: Write a program to add multiple elements to the set.
This tutorial will study the major differences between lists and tuples and how to handle these two data structures.
Lists and tuples are types of data structures that hold one or more than one objects or items in a predefined order. We can contain objects of any data type in a list or tuple, including the null data type defined by the None Keyword.
What is a List?
In other programming languages, list objects are declared similarly to arrays. Lists don’t have to be homogeneous all the time, so they can simultaneously store items of different data types. This makes lists the most useful tool. The list is a kind of container data Structure of Python that is used to hold numerous pieces of data simultaneously. Lists are helpful when we need to iterate over some elements and keep hold of the items.
What is a Tuple?
A tuple is another data structure to store the collection of items of many data types, but unlike mutable lists, tuples are immutable. A tuple, in other words, is a collection of items separated by commas. Because of its static structure, the tuple is more efficient than the list.
Differences between Lists and Tuples
In most cases, lists and tuples are equivalent. However, there are some important differences to be explored in this article.
List and Tuple Syntax Differences
The syntax of a list differs from that of a tuple. Items of a tuple are enclosed by parentheses or curved brackets (), whereas items of a list are enclosed by square brackets [].
Example Code
# Python code to show the difference between creating a list and a tuple
list_ = [4, 5, 7, 1, 7]
tuple_ = (4, 1, 8, 3, 9)
print("List is: ", list_)
print("Tuple is: ", tuple_)
Output:List is: [4, 5, 7, 1, 7] Tuple is: (4, 1, 8, 3, 9)
We declared a variable named list_, which contains a certain number of integers ranging from 1 to 10. The list is enclosed in square brackets []. We also created a variable called tuple_, which holds a certain number of integers. The tuple is enclosed in curly brackets (). The type() method in Python returns the data type of the data structure or object passed to it.
Example Code
# Code to print the data type of the data structure using the type() function
print( type(list_) )
print( type(tuple_) )
Output:<class ‘list’> <class ‘tuple’>
Mutable List vs. Immutable Tuple
An important difference between a list and a tuple is that lists are mutable, whereas tuples are immutable. What exactly does this imply? It means a list’s items can be changed or modified, whereas a tuple’s items cannot be changed or modified.
We can’t employ a list as a key of a dictionary because it is mutable. This is because a key of a Python dictionary is an immutable object. As a result, tuples can be used as keys to a dictionary if required.
Let’s consider the example highlighting the difference between lists and tuples in immutability and mutability.
Example Code
# Updating the element of list and tuple at a particular index
# creating a list and a tuple
list_ = ["Python", "Lists", "Tuples", "Differences"]
tuple_ = ("Python", "Lists", "Tuples", "Differences")
# modifying the last string in both data structures
list_[3] = "Mutable"
print( list_ )
try:
tuple_[3] = "Immutable"
print( tuple_ )
except TypeError:
print( "Tuples cannot be modified because they are immutable" )
Output:[‘Python’, ‘Lists’, ‘Tuples’, ‘Mutable’] Tuples cannot be modified because they are immutable
We altered the string of list_ at index 3 in the above code, which the Python interpreter updated at index 3 in the output. Also, we tried to modify the last index of the tuple in a try block, but since it raised an error, we got output from the except block. This is because tuples are immutable, and the Python interpreter raised TypeError on modifying the tuple.
Size Difference
Since tuples are immutable, Python allocates bigger chunks of memory with minimal overhead. Python, on the contrary, allots smaller memory chunks for lists. The tuple would therefore have less memory than the list. If we have a huge number of items, this makes tuples a little more memory-efficient than lists.
For example, consider creating a list and a tuple with the identical items and comparing their sizes:
Example Code
# Code to show the difference in the size of a list and a tuple
#creating a list and a tuple
list_ = ["Python", "Lists", "Tuples", "Differences"]
tuple_ = ("Python", "Lists", "Tuples", "Differences")
# printing sizes
print("Size of tuple: ", tuple_.__sizeof__())
print("Size of list: ", list_.__sizeof__())
Output:Size of tuple: 28 Size of list: 52
Available Functions
Tuples have fewer built-in functions than lists. We may leverage the in-built function dir([object] to access all the corresponding methods for the list and tuple.
As we can observe, a list has many more methods than a tuple. With intrinsic functions, we can perform insert and pop operations and remove and sort items from the list not provided in the tuple.
Tuples and Lists: Key Similarities
They both hold collections of items and are heterogeneous data types, meaning they can contain multiple data types simultaneously.
They’re both ordered, which implies the items or objects are maintained in the same order as they were placed until changed manually.
Because they’re both sequential data structures, we can iterate through the objects they hold; hence, they are iterables.
An integer index, enclosed in square brackets [index], can be used to access objects of both data types.
A comma-separated group of items is called a Python triple. The ordering, settled items, and reiterations of a tuple are to some degree like those of a rundown, but in contrast to a rundown, a tuple is unchanging.
The main difference between the two is that we cannot alter the components of a tuple once they have been assigned. On the other hand, we can edit the contents of a list.
Example
(“Suzuki”, “Audi”, “BMW”,” Skoda “) is a tuple.
Features of Python Tuple
Tuples are an immutable data type, meaning their elements cannot be changed after they are generated.
Each element in a tuple has a specific order that will never change because tuples are ordered sequences.
Forming a Tuple:
All the objects-also known as “elements”-must be separated by a comma, enclosed in parenthesis (). Although parentheses are not required, they are recommended.
Any number of items, including those with various data types (dictionary, string, float, list, etc.), can be contained in a tuple.
Code
# Python program to show how to create a tuple
# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)
# Creating tuple having integers
int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)
# Creating a tuple having objects of different data types
mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)
# Creating a nested tuple
nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)
Output:Empty tuple: () Tuple with integers: (4, 6, 8, 10, 12, 14) Tuple with different data types: (4, ‘Python’, 9.3) A nested tuple: (‘Python’, {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Parentheses are not necessary for the construction of multiples. This is known as triple pressing.
Code
# Python program to create a tuple without using parentheses
# Creating a tuple
tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]
# Displaying the tuple created
print(tuple_)
# Checking the data type of object tuple_
print(type(tuple_) )
# Trying to modify tuple_
try:
tuple_[1] = 4.2
except:
print(TypeError )
The development of a tuple from a solitary part may be complex.
Essentially adding a bracket around the component is lacking. A comma must separate the element to be recognized as a tuple.
Code
# Python program to show how to create a tuple having a single element
single_tuple = ("Tuple")
print( type(single_tuple) )
# Creating a tuple that has only one element
single_tuple = ("Tuple",)
print( type(single_tuple) )
# Creating tuple without parentheses
single_tuple = "Tuple",
print( type(single_tuple) )
A tuple’s objects can be accessed in a variety of ways.
Indexing
Indexing We can use the index operator [] to access an object in a tuple, where the index starts at 0.
The indices of a tuple with five items will range from 0 to 4. An Index Error will be raised assuming we attempt to get to a list from the Tuple that is outside the scope of the tuple record. An index above four will be out of range in this scenario.
Because the index in Python must be an integer, we cannot provide an index of a floating data type or any other type. If we provide a floating index, the result will be TypeError.
The method by which elements can be accessed through nested tuples can be seen in the example below.
Code
# Python program to show how to access tuple elements
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print(tuple_[0])
print(tuple_[1])
# trying to access element index more than the length of a tuple
try:
print(tuple_[5])
except Exception as e:
print(e)
# trying to access elements through the index of floating data type
try:
print(tuple_[1.0])
except Exception as e:
print(e)
# Creating a nested tuple
nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))
# Accessing the index of a nested tuple
print(nested_tuple[0][3])
print(nested_tuple[1][1])
Output:Python Tuple tuple index out of range tuple indices must be integers or slices, not float l 6
Negative Indexing
Python’s sequence objects support negative indexing.
The last thing of the assortment is addressed by – 1, the second last thing by – 2, etc.
Code
# Python program to show how negative indexing works in Python tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
# Printing elements using negative indices
print("Element at -1 index: ", tuple_[-1])
print("Elements between -4 and -1 are: ", tuple_[-4:-1])
Output:Element at -1 index: Collection Elements between -4 and -1 are: (‘Python’, ‘Tuple’, ‘Ordered’)
Slicing
Tuple slicing is a common practice in Python and the most common way for programmers to deal with practical issues. Look at a tuple in Python. Slice a tuple to access a variety of its elements. Using the colon as a straightforward slicing operator (:) is one strategy.
To gain access to various tuple elements, we can use the slicing operator colon (:).
Code
# Python program to show how slicing works in Python tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Using slicing to access elements of the tuple
print("Elements between indices 1 and 3: ", tuple_[1:3])
# Using negative indexing in slicing
print("Elements between indices 0 and -4: ", tuple_[:-4])
# Printing the entire tuple by using the default start and end values.
print("Entire tuple: ", tuple_[:])
Output:Elements between indices 1 and 3: (‘Tuple’, ‘Ordered’) Elements between indices 0 and -4: (‘Python’, ‘Tuple’) Entire tuple: (‘Python’, ‘Tuple’, ‘Ordered’, ‘Immutable’, ‘Collection’, ‘Objects’)
Deleting a Tuple
A tuple’s parts can’t be modified, as was recently said. We are unable to eliminate or remove tuple components as a result.
However, the keyword del can completely delete a tuple.
Code
# Python program to show how to delete elements of a Python tuple
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Deleting a particular element of the tuple
try:
del tuple_[3]
print(tuple_)
except Exception as e:
print(e)
# Deleting the variable from the global space of the program
del tuple_
# Trying accessing the tuple after deleting it
try:
print(tuple_)
except Exception as e:
print(e)
Output:‘tuple’ object does not support item deletion name ‘tuple_’ is not defined
Repetition Tuples in Python
Code
# Python program to show repetition in tuples
tuple_ = ('Python',"Tuples")
print("Original tuple is: ", tuple_)
# Repeting the tuple elements
tuple_ = tuple_ * 3
print("New tuple is: ", tuple_)
Output:Original tuple is: (‘Python’, ‘Tuples’) New tuple is: (‘Python’, ‘Tuples’, ‘Python’, ‘Tuples’, ‘Python’, ‘Tuples’)
Tuple Methods
Like the list, Python Tuples is a collection of immutable objects. There are a few ways to work with tuples in Python. With some examples, this essay will go over these two approaches in detail.
The following are some examples of these methods.
Count () Method
The times the predetermined component happens in the Tuple is returned by the count () capability of the Tuple.
Code
# Creating tuples
T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
# counting the appearance of 3
res = T1.count(2)
print('Count of 2 in T1 is:', res)
# counting the appearance of java
res = T2.count('java')
print('Count of Java in T2 is:', res)
Output:Count of 2 in T1 is: 5 Count of java in T2 is: 2
Index() Method:
The Index() function returns the first instance of the requested element from the Tuple.
Parameters:
The thing that must be looked for.
Start: (Optional) the index that is used to begin the final (optional) search: The most recent index from which the search is carried out
Index Method
Code
# Creating tuples
Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
res = Tuple_data.index(3)
print('First occurrence of 1 is', res)
# getting the index of 3 after 4th
# index
res = Tuple_data.index(3, 4)
print('First occurrence of 1 after 4th index is:', res)
Output:First occurrence of 1 is 2 First occurrence of 1 after 4th index is: 6
Tuple Membership Test
Utilizing the watchword, we can decide whether a thing is available in the given Tuple.
Code
# Python program to show how to perform membership test for tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
# In operator
print('Tuple' in tuple_)
print('Items' in tuple_)
# Not in operator
print('Immutable' not in tuple_)
print('Items' not in tuple_)
Output:True False False True
Iterating Through a Tuple
A for loop can be used to iterate through each tuple element.
Code
# Python program to show how to iterate over tuple elements
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
# Iterating over tuple elements using a for loop
for item in tuple_:
print(item)
Output:Python Tuple Ordered Immutable
Changing a Tuple
Tuples, instead of records, are permanent articles.
This suggests that once the elements of a tuple have been defined, we cannot change them. However, the nested elements can be altered if the element itself is a changeable data type like a list.
Multiple values can be assigned to a tuple through reassignment.
Code
# Python program to show that Python tuples are immutable objects
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", [1,2,3,4])
# Trying to change the element at index 2
try:
tuple_[2] = "Items"
print(tuple_)
except Exception as e:
print( e )
# But inside a tuple, we can change elements of a mutable object
tuple_[-1][2] = 10
print(tuple_)
# Changing the whole tuple
tuple_ = ("Python", "Items")
print(tuple_)
Output:‘tuple’ object does not support item assignment (‘Python’, ‘Tuple’, ‘Ordered’, ‘Immutable’, [1, 2, 10, 4]) (‘Python’, ‘Items’)
The + operator can be used to combine multiple tuples into one. This phenomenon is known as concatenation.
We can also repeat the elements of a tuple a predetermined number of times by using the * operator. This is already demonstrated above.
The aftereffects of the tasks + and * are new tuples.
Code
# Python program to show how to concatenate tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
# Adding a tuple to the tuple_
print(tuple_ + (4, 5, 6))
Due to tuples, the code is protected from accidental modifications. It is desirable to store non-changing information in “tuples” instead of “records” if a program expects it.
A tuple can be used as a dictionary key if it contains immutable values like strings, numbers, or another tuple. “Lists” cannot be utilized as dictionary keys because they are mutable.