SSE-256 Python Notes
SSE-256 Python Notes
Introduction to Python
It is used for:
mathematics,
system scripting.
These languages can fulfill more than one purpose, for example they can be apt for
mathematical calculations, research work and application development at the same
time.
For example
o Java can be used for developing interactive webpages as well as making games.
o C++ can be used for writing applications as well as developing system programs.
o Python, Perl, Ruby can be used for web programming as well as development of desktop
applications.
A list of various general purpose programming languages:
o Java
o Ruby
o Python
o C
o C++
o D
o Dart
o C#
What is an IDE?
An IDE, or Integrated Development Environment, enables programmers to
consolidate the different aspects of writing a computer program.
Syntax Highlighting
An IDE that knows the syntax of your language can provide visual cues.
Keywords, words that have special meaning like class in Java, are highlighted
with different colors.
Autocomplete
When the IDE knows your programming language, it can anticipate what
you’re going to type next!
We’ve seen statements with System.out.println() quite a bit so far. In an IDE, we
might see System as an autocomplete option after only typing Sy. This saves
keystrokes so the programmer can focus on logic in their code.
Python - IDLE
IDLE (Integrated Development and Learning Environment) is an
integrated development environment (IDE) for Python. The Python
installer for Windows contains the IDLE module by default.
To start an IDLE interactive shell, search for the IDLE icon in the
start menu and double click on it.
Python IDLE
This will open IDLE, where you can write and execute the Python
scripts, as shown below.
Python IDLE
To execute a Python script, create a new file by selecting File -> New
File from the menu.
Enter multiple statements and save the file with extension .py using
File -> Save. For example, save the following code as hello.py.
Python Script in IDLE
Now, press F5 to run the script in the editor window. The IDLE shell
will show the output.
A python compiler does a lot less work than the interpreter, however. Codes are
compiled in to a byte code which means a compiler isn’t always necessary.
The interpreter will read the python code and then look at each line of code created to
verify the instructions and ensure they’re formatted correctly. If there are any errors
within the software, they will appear as each line is translated. The interpreter can
execute the codes immediately through the standard input.
Essentially, the python interpreter reads and executes codes instantly and does so in
interactive mode. It can also be script, source or pre-compiled code. Installing python is
a simple process and takes only a few minutes. If you want to install python, follow the
instructions given.
Remember, the interpreter can be far quicker than the compiler because it translates
the code and executes the program at the same time. A compiler requires an additional
step to complete the process. Also, compilers are used in program languages like C+
and are generally the same no matter which version number of python is being used.
Interpreter uses interactive mode and python C languages. C command is vastly
popular with python and you can easily select a file name to bring up the program.
However, compilers are faster than interpreters. Since a compiler opts to translate the
entire program at once (rather than line-by-line like interpreter), it makes the process
quicker. First Python interpreters can be fairly quick, but again, the compiler translates
the codes at one time so it is faster than the interpreters. It may impact web
development and computer programming later also. Sys.argv is another program
widely used in python and sys.argv is a popular choice. You could use the command
line to open this file up.
When the compiler picks up an error, it will stop the translation of the code and will take
steps to remove the error. However, once it does, the coding is translated again. The
compiler shows all of the errors found at the same time and it may make it difficult to
know where the errors took place. There are slight differences for translation, but can
make a huge difference later with python online. The interactive mode is easy to use
and runs automatically, use the primary prompt to select a file to open.
To run Python scripts, select a script name like sys.argv, by using the Python
command. You need to open the command line and type the path to the script file, so
input a script name. Choose the relevant script (like sys.argv) and that’s it.
The interactive mode can be easy to use. You can repeat the process again with a
different command line if you want to use different scripts. Or use primary prompt to
choose a new script or file name.
Conclusion
Understanding what is interpreter in python is easy. An interpreter for python is an
important concept for web development and computer programming. A Python
interpreter and compiler are quite similar to one another. Essentially, they both do the
same job, but in very different ways. Each has a slightly different procedure when
generating a source code, but the end result remains the same.
Python interpreter uses a line-by-line approach whereas the compiler opts for a whole
program approach. They both have their advantages and disadvantages but they make
the overall process quicker and easier for all. Even beginners can understand sys.argv
and C Command by using Python.
To declare an encoding other than the default one, a special comment line should be
added as the first line of the file. The syntax is as follows:
For example, to declare that Windows-1252 encoding is to be used, the first line of your
source code file should be:
One exception to the first line rule is when the source code starts with a UNIX
“shebang” line. In this case, the encoding declaration should be added as the second
line of the file. For example:
#!/usr/bin/env python3
# -*- coding: cp1252 -*-
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
Python can connect to database systems. It can also read and modify
files.
Python can be used to handle big data and perform complex
mathematics.
Real-World Examples:
1) NASA (National Aeronautics and Space Agency): One of Nasa’s Shuttle
Support Contractors, United Space Alliance developed a Workflow
Automation System (WAS) which is fast. Internal Resources Within critical
project stated that:
“Python allows us to tackle the complexity of programs like the WAS without
getting bogged down in the language”.
2) Netflix: There are various projects in Netflix which use python as follow:
2) Game Development: PySoy and PyGame are two python libraries that are
used for game development
4) Desktop GUI: Desktop GUI offers many toolkits and frameworks using
which we can build desktop applications.PyQt, PyGtk, PyGUI are some of the
GUI frameworks.
Advantages :
1. Presence of third-party modules
2. Extensive support libraries(NumPy for numerical calculations, Pandas for
data analytics etc)
3. Open source and community development
4. Versatile, Easy to read, learn and write
5. User-friendly data structures
6. High-level language
7. Dynamically typed language(No need to mention data type based on the
value assigned, it takes data type)
8. Object-oriented language
9. Portable and Interactive
10. Ideal for prototypes – provide more functionality with less coding
11. Highly Efficient(Python’s clean object-oriented design provides enhanced
process control, and the language is equipped with excellent text processing
and integration capabilities, as well as its own unit testing framework, which
makes it more efficient.)
12. (IoT)Internet of Things Opportunities
13. Interpreted Language
14. Portable across Operating systems
Applications :
1. GUI based desktop applications
2. Graphic design, image processing applications, Games, and Scientific/
computational Applications
3. Web frameworks and applications
4. Enterprise and Business applications
5. Operating Systems
6. Education
7. Database Access
8. Language Development
9. Prototyping
10. Software Development
A Remote Desktop Connection app (use if you are installing Python on a remote Windows
server)
The version you need depends on what you want to do in Python. For example, if you are
working on a project coded in Python version 2.6, you probably need that version. If you are
starting a project from scratch, you have the freedom to choose.
If you are learning to code in Python, we recommend you download both the latest version of
Python 2 and 3. Working with Python 2 enables you to work on older projects or test new
projects for backward compatibility.
3. Select a link to download either the Windows x86-64 executable installer or Windows x86
executable installer. The download is approximately 25MB.
Step 3: Run Executable Installer
1. Run the Python Installer once downloaded. (In this example, we have downloaded Python
3.7.3.)
2. Make sure you select the Install launcher for all users and Add Python 3.7 to
PATH checkboxes. The latter places the interpreter in the execution path. For older versions of
Python that do not support the Add Python to Path checkbox, see Step 6.
4. The next dialog will prompt you to select whether to Disable path length limit. Choosing this
option will allow Python to bypass the 260-character MAX_PATH limit. Effectively, it will
enable Python to use long path names.
The Disable path length limit option will not affect any other system settings. Turning it on will
resolve potential name length issues that may arise with Python projects developed in Linux.
We recommend using Pip for most Python packages, especially when working in virtual
environments.
3. Enter pip -V in the console. If Pip was installed successfully, you should see the following
output:
Pip has not been installed yet if you get the following output:
Setting up the Python path to system variables alleviates the need for using full paths. It instructs
Windows to look through all the PATH folders for “python” and find the install folder that
contains the python.exe file.
5. Click Edit.
6. Select the Variable value field. Add the path to the python.exe file preceded with
a semicolon (;). For example, in the image below, we have added ";C:\Python34."
By setting this up, you can execute Python scripts like this: Python script.py
Python software packages are installed system-wide by default. Consequently, whenever a single
project-specific package is changed, it changes for all your Python projects. You would want to
avoid this, and having separate virtual environments for each project is the easiest solution.
To install virtualnv:
What is variable
It is a place where we can store values. Instead of using the values directly, we can refer the
variable name where the actual values are stored.
Example
> x = 2 === > here X is Variable
> name = 'John' === > here NAME is variable
What is Expression
Example
> 10
>x
> y = x + 10
What is Statement
It is a logical unit of code that can be executed at the Python interpreter. When we type statement at
the command promt, it will execute the code in the statement then provides the results, as long as
the code is clean. We can execute code that is in a file. In general these file contains scripts, these
scripts are combination of statements to perform units of work.
Example
> print("Hello World")
Hello World
A value is one of the basic things a program works with, like a letter or a number. The values we
have seen so far are 1, 2, and 'Hello, World!'.
These values belong to different types: 2 is an integer, and 'Hello, World!' is a string, so-
called because it contains a “string” of letters. You (and the interpreter) can identify strings
because they are enclosed in quotation marks.
>>> print 4
4
If you are not sure what type a value has, the interpreter can tell you.
Not surprisingly, strings belong to the type str and integers belong to the type int. Less
obviously, numbers with a decimal point belong to a type called float, because these numbers
are represented in a format called floating-point.
>>> type(3.2)
<type 'float'>
What about values like '17' and '3.2'? They look like numbers, but they are in quotation
marks like strings.
>>> type('17')
<type 'str'>
>>> type('3.2')
<type 'str'>
They’re strings.
When you type a large integer, you might be tempted to use commas between groups of three
digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:
Well, that’s not what we expected at all! Python interprets 1,000,000 as a comma-separated
sequence of integers, which it prints with spaces between.
This is the first example we have seen of a semantic error: the code runs without producing an
error message, but it doesn’t do the “right” thing.
Variables
This example makes three assignments. The first assigns a string to a new variable
named message; the second gives the integer 17 to n; the third assigns the (approximate) value
of π to pi.
A common way to represent variables on paper is to write the name with an arrow pointing to the
variable’s value. This kind of figure is called a state diagram because it shows what state each
of the variables is in (think of it as the variable’s state of mind). This diagram shows the result of
the previous example:
To display the value of a variable, you can use a print statement:
>>> print n
17
>>> print pi
3.14159265359
>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>
Programmers generally choose names for their variables that are meaningful—they document
what the variable is used for.
Variable names can be arbitrarily long. They can contain both letters and numbers, but they have
to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin variable
names with a lowercase letter (you’ll see why later).
The underscore character (_) can appear in a name. It is often used in names with multiple
words, such as my_name or airspeed_of_unladen_swallow.
76trombones is illegal because it does not begin with a letter. more@ is illegal because it contains
an illegal character, @. But what’s wrong with class?
It turns out that class is one of Python’s keywords. The interpreter uses keywords to recognize
the structure of the program, and they cannot be used as variable names.
You might want to keep this list handy. If the interpreter complains about one of your variable
names and you don’t know why, see if it is on this list.
Statements
A statement is a unit of code that the Python interpreter can execute. We have seen two kinds of
statements: print and assignment.
When you type a statement in interactive mode, the interpreter executes it and displays the result,
if there is one.
A script usually contains a sequence of statements. If there is more than one statement, the
results appear one at a time as the statements execute.
print 1
x = 2
print x
1
2
Comments
As programs get bigger and more complicated, they get more difficult to read. Formal languages
are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or
why.
For this reason, it is a good idea to add notes to your programs to explain in natural language
what the program is doing. These notes are called comments, and they start with the # symbol:
In this case, the comment appears on a line by itself. You can also put comments at the end of a
line:
Everything from the # to the end of the line is ignored—it has no effect on the program.
Comments are most useful when they document non-obvious features of the code. It is
reasonable to assume that the reader can figure out what the code does; it is much more useful to
explain why.
v = 5 # assign 5 to v
v = 5 # velocity in meters/second.
Good variable names can reduce the need for comments, but long names can make complex
expressions hard to read, so there is a tradeoff.
Debugging
Runtime error:
The second type of error is a runtime error, so
called because the error does not appear until after the program has
started running. These errors are also called exceptions
because they usually indicate that something exceptional (and bad)
has happened.
Runtime errors are rare in the simple programs you will see in the
first few chapters, so it might be a while before you encounter one.
Semantic error:
The third type of error is “semantic”, which
means related to meaning. If there is a semantic error in your
program, it will run without generating error messages, but it will
not do the right thing. It will do something else. Specifically,
it will do what you told it to do.
Identifying semantic errors can be tricky because it requires you to work
backward by looking at the output of the program and trying to figure
out what it is doing.
Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used
in the program. The rules to name an identifier are given below.
We don't need to declare explicitly variable in Python. When we assign any value to the
variable, that variable is declared automatically.
Object References
It is necessary to understand how the Python interpreter works when we declare a
variable. The process of treating variables is somewhat different from many other
programming languages.
Python is the highly object-oriented programming language; that's why every data item
belongs to a specific type of class. Consider the following example.
1. print("John")
Output:
John
The Python object creates an integer object and displays it to the console. In the above
print statement, we have created a string object. Let's check the type of it using the
Python built-in type() function.
1. a = 50
a = 50
b=a
The variable b refers to the same object that a points to because Python does not create
another object.
Let's assign the new value to b. Now both variables will refer to the different objects.
a = 50
b =100
Python manages memory efficiently if we assign the same variable to two different
values.
Object Identity
In Python, every created object identifies uniquely in Python. Python provides the
guaranteed that no two objects will have the same identifier. The built-in id() function, is
used to identify the object identifier. Consider the following example.
1. a = 50
2. b=a
3. print(id(a))
4. print(id(b))
5. # Reassigned variable a
6. a = 500
7. print(id(a))
Output:
140734982691168
140734982691168
2822056960944
We assigned the b = a, a and b both point to the same object. When we checked by
the id() function it returned the same number. We reassign a to 500; then it referred to
the new object identifier.
Variable Names
We have already discussed how to declare the valid variable. Variable names can be any
length can have uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore
character(_). Consider the following example of valid variables names.
1. name = "Devansh"
2. age = 20
3. marks = 80.50
4.
5. print(name)
6. print(age)
7. print(marks)
Output:
Devansh
20
80.5
1. name = "A"
2. Name = "B"
3. naMe = "C"
4. NAME = "D"
5. n_a_m_e = "E"
6. _name = "F"
7. name_ = "G"
8. _name_ = "H"
9. na56me = "I"
10.
11. print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, n
a56me)
Output:
A B C D E D E F G F I
In the above example, we have declared a few valid variable names such as name,
_name_ , etc. But it is not recommended because when we try to read code, it may
create confusion. The variable name should be descriptive to make code more readable.
o Camel Case - In the camel case, each word or abbreviation in the middle of
begins with a capital letter. There is no intervention of whitespace. For example -
nameOfStudent, valueOfVaraible, etc.
o Pascal Case - It is the same as the Camel Case, but here the first word is also
capital. For example - NameOfStudent, etc.
o Snake Case - In the snake case, Words are separated by the underscore. For
example - name_of_student, etc.
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is
also known as multiple assignments.
We can apply multiple assignments in two ways, either by assigning a single value to
multiple variables or assigning multiple values to multiple variables. Consider the
following example.
Eg:
1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)
Output:
50
50
50
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
5
10
15
Local Variable
Local variables are the variables that declared inside the function and have scope within
the function. Let's understand the following example.
Example -
1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8.
9. # Calling a function
10. add()
Output:
Explanation:
In the above code, we declared a function named add() and assigned a few variables
within the function. These variables will be referred to as the local variables which have
scope only inside the function. If we try to use them outside the function, we get a
following error.
1. add()
2. # Accessing local variable outside the function
3. print(a)
Output:
We tried to use local variable outside their scope; it threw the NameError.
Global Variables
Global variables can be used throughout the program, and its scope is in the entire
program. We can use global variables inside or outside the function.
A variable declared outside the function is the global variable by default. Python
provides the global keyword to use global variable inside the function. If we don't use
the global keyword, the function treats it as a local variable. Let's understand the
following example.
Example -
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
In the above code, we declare a global variable x and assign a value to it. Next, we
defined a function and accessed the declared variable using the global keyword inside
the function. Now we can modify its value. Then, we assigned a new string value to the
variable x.
Now, we called the function and proceeded to print x. It printed the as newly assigned
value of x.
Delete a variable
We can delete the variable using the del keyword. The syntax is given below.
Syntax -
1. del <variable_name>
In the following example, we create a variable x and assign value to it. We deleted
variable x, and print it, we get the error "variable x is not defined". The variable x will
no longer use in future.
Example -
1. # Assigning a value to x
2. x=6
3. print(x)
4. # deleting a variable.
5. del x
6. print(x)
Output:
6
Traceback (most recent call last):
File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py",
line 389, in
print(x)
NameError: name 'x' is not defined
Print Single and Multiple Variables in Python
We can print multiple variables within the single print statement. Below are the example
of single and multiple printing values.
Output:
5
5
1. a=5
2. b=6
3. # printing multiple variables
4. print(a,b)
5. # separate the variables by the comma
6. Print(1, 2, 3, 4, 5, 6, 7, 8)
Output:
5 6
1 2 3 4 5 6 7 8
print(1 + 1)
print(len("hello"))
In this example len is a built-in Python function that returns the number of
characters in a string. We’ve previously seen the print and the type functions, so
this is our third example of a function!
y = 3.14
x = len("hello")
print(x)
print(y)
If we take a look at this same example in the Python shell, we will see one of the
distinct differences between statements and expressions.
>>> y = 3.14
>>> x = len("hello")
>>> print(x)
5
>>> print(y)
3.14
>>> y
3.14
>>>
Note that when we enter the assignment statement, y = 3.14, only the prompt is
returned. There is no value. This is due to the fact that statements, such as the
assignment statement, do not return a value. They are simply executed.
On the other hand, the result of executing the assignment statement is the
creation of a reference from a variable, y, to a value, 3.14. When we execute the
print function working on y, we see the value that y is referring to. In fact,
evaluating y by itself results in the same response.
The evaluation of a statement does not changes state The execution of a statement changes state
Example: >>> x = 3
Example: >>> a + 16 >>> print(x)
>>> 20
Output: 3
Conditional Execution:-
1. If the statement
2. If else statement
3. Nested if statement
4. If…Elif ladder
If Statement
Example – 1
num = 5
if num > 0:
print(num, "is a positive number.")
print("This statement is true.")
#When we run the program, the output will be:
5 is a positive number.
This statement is true.
Example – 2
a = 25
b = 170
if b > a:
print("b is greater than a")
output : b is greater than a
If Else Statement
This statement is used when both the true and false parts of a given condition
are specified to be executed. When the condition is true, the statement inside
the if block is executed; if the condition is false, the statement outside the if
block is executed.
If…Elif..else Statement
In this case, the If condition is evaluated first. If it is false, the Elif statement
will be executed; if it also comes false, the Else statement will be executed.
The If…Elif..else statement in Python has the subsequent syntax:
if condition :
Body of if
elif condition :
Body of elif
else:
Body of else
Example-1
num = 8
if num >= 0:
if num == 0:
print("zero")
else:
print("Positive number")
else:
print("Negative number")
output: Positive number
Example-2
price=100
quantity=10
amount = price*quantity
if amount > 200:
if amount >1000:
print("The amount is greater than 1000")
else:
if amount 800:
print("The amount is between 800 and 1000")
elif amount 600:
print("The amount is between 600 and 1000")
else:
print("The amount is between 400 and 1000")
elif amount == 200:
print("Amount is 200")
else:
print("Amount is less than 200")
The output : “The amount is between 400 and 1000.”
It is used to mention If-else statements in one line in which there is only one
statement to execute in both if and else blocks. In simple words, If you have
only one statement to execute, one for if, and one for else, you can put it all
on the same line.
To summarise,
· The If the condition is used to print the result when only one of the conditions
listed is true or false.
· When one of the conditions is false, the If-else condition is used to print the
statement.
Example
function(argument){
switch(argument) {
case 0:
return "This is Case Zero";
case 1:
return " This is Case One";
case 2:
return " This is Case Two ";
default:
return "nothing";
};
};
if __name__ == "__main__":
argument = 1
print (SwitchExample(argument))
Python Functions
What is a function in Python?
In Python, a function is a group of related statements that performs a specific
task.
Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
6. One or more valid python statements that make up the function body.
Statements must have the same indentation level (usually 4 spaces).
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
How to call a function in python?
>>> greet('Paul')
Hello, Paul. Good morning!
Try running the above code in the Python program with the function definition
to see the output.
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
greet('Paul')
Note: In python, the function definition should always be present before the
function call. Otherwise, we will get an error. For example,
# function call
greet('Paul')
# function definition
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
# Erro: name 'greet' is not defined
Docstrings
The first string after the function header is called the docstring and is short for
documentation string. It is briefly used to explain what a function does.
>>> print(greet.__doc__)
return [expression_list]
This statement can contain an expression that gets evaluated and the value is
returned. If there is no expression in the statement or the return statement
itself is not present inside a function, then the function will return
the None object.
For example:
>>> print(greet("May"))
Hello, May. Good morning!
None
Here, None is the returned value since greet() directly prints the name and
no return statement is used.
Example of return
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
Output
2
4
Types of Functions
Basically, we can divide functions into the following two types:
def add_numbers(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6
Output
Here, we have defined the function my_addition() which adds two numbers and
returns the result.
This is our user-defined function. We could have multiplied the two numbers
inside our function (it's all up to us). But this operation would not be consistent
with the name of the function. It would create ambiguity.
It is always a good idea to name functions according to the task they perform.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
Live Demo
#!/usr/bin/python
Anonymous functions:
In Python, an anonymous function means that a function is without a name. As
we already know the def keyword is used to define the normal functions and the
lambda keyword is used to create anonymous functions. Please see this for
details.
print(cube(7))
print(cube_v2(7))
Output
343
Arguments in Functions
The argument is a value that is passed to the function when it’s called.
In other words on the calling side, it is an argument and on the function side it
is a parameter.
Step 1) Arguments are declared in the function definition. While calling the
function, you can pass the values for that args as shown below
Step 2) To declare a default value of an argument, assign it a value at
function definition.
Example: x has no default values. Default values of y=0. When we supply only
one argument while calling multiply function, Python assigns the supplied
value to x while keeping the value of y=0. Hence the multiply of x*y=0
Step 3) This time we will change the value to y=2 instead of the default value
y=0, and it will return the output as (4×2)=8.
Step 4) You can also change the order in which the arguments can be passed
in Python. Here we have reversed the order of the value x and y to x=4 and
y=2.
Function Arguments
You can call a function by using the following types of formal arguments −
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the
function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it
gives a syntax error as follows −
Live Demo
#!/usr/bin/python
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters.
You can also make keyword calls to the printme() function in the following ways −
Live Demo
#!/usr/bin/python
Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an idea on
default arguments, it prints default age if it is not passed −
Live Demo
#!/usr/bin/python
Variable-length arguments
You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-length arguments and are
not named in the function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional arguments
are specified during the function call. Following is a simple example −
Live Demo
#!/usr/bin/python
Recursion
Python also accepts function recursion, which means a defined function can call
itself.
To a new developer it can take some time to work out how exactly this works,
best way to find out is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
Here, we are maintaining reference of the passed object and appending values in the
same object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the
reference is being overwritten inside the called function.
Live Demo
#!/usr/bin/python
The parameter mylist is local to the function changeme. Changing mylist within the
function does not affect mylist. The function accomplishes nothing and finally this
would produce the following result −
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Now that we know the in-built functions provided by Python that are used for explicit
type conversion, let’s see the syntax for explicit type conversion:
(required_data type)(expression)
Let’s go over the following examples for explicit type conversion in Python.
# adding string and integer data types using explicit type
conversion
a = 100
b = “200”
result1 = a + b
b = int(b)
result2 = a + b
print(result2)
Output:
Traceback (most recent call last):
File “”, line 1, in
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’
300
In the above example, variable a is of the number data type and variable b is of the
string data type. When we try to add these two integers and store the value in a variable
named result1, a TypeError occurs as shown in the output. So, in order to perform this
operation, we have to use explicit type casting.
As we can see in the above code block, we have converted the variable b into int type
and then added variables a and b. The sum is stored in the variable named result2, and
when printed it displays 300 as output, as we can see in the output block.
Type conversion is the process of converting a data type into another data
type.
Implicit type conversion is performed by a Python interpreter only.
o Using functions, we can avoid rewriting the same logic/code again and again in a
program.
o We can call Python functions multiple times in a program and anywhere in a
program.
o We can track a large Python program easily when it is divided into multiple
functions.
o Reusability is the main achievement of Python functions.
o However, Function calling is always overhead in a Python program.
Flow of Execution
The flow of execution basically refers to the order in which statements
are executed. That is to say, execution always starts at the first
statement of the program. Moreover, statements execute one at a time. It
happens in order, from top to bottom.
Further, functions definitions do not alter the flow of execution of the
program. However, it remembers the statements inside the function do
not execute until the functions is called.
However, one must skip the statements of the function definition until
they reach a point where that function is called.
ITERATIONS:
A computer program consists of line-by-line instructions. The computer
performs those instructions line-by-line. However, some instructions
may be repetitive with a common pattern. Recursion or iteration helps
one to write a few lines of codes to perform such repetitive tasks.
Suppose a Python list with five-string elements. We wish to print the
elements one in a line. This operation needs five lines of codes.
It can be observed that the five lines of codes follow the same pattern.
The only difference in each line is the index of the list elements. What if
this list contains 100 or 1000 elements? Coding will become a tedious
task. These kinds of problems are resolved through either iteration or
recursion. Here, the iterative form of the above codes is as follows.
Iteration in Python
Iterations are performed through ‘for’ and ‘while’ loops. Iterations
execute a set of instructions repeatedly until some limiting criteria is
met. In contrast to recursion, iteration does not require temporary
memory to keep on the results of each iteration. Rather, programmers
should define a variable (a number, or list, or string, or any mutable
data type) well before the start of iterative calls to collect the results (if
there are such arithmetic results) during each iteration.
Factorial of an Integer
Calculating factorial is a popular use case to understand iteration
For instance, we wish to calculate the factorial of 10. It can be
determined as 1*2*3*4*5*6*7*8*9*10 = 3628800. This can be viewed
as 10 subproblems of multiplying an incrementing integer to a final
result.
num = 0
print("The number is", num)
num = num + 1
print("The number is now", num)
num = num + 1
print("The number is up to", num)
num = num + 20
print("The number ends at", num)
How does that look? We re-use the num variable again and again, changing it each
time. One way of thinking about it:
o It then saves that 1 back into num, throwing away the old value for num
o Now num is 1!
o It then saves that 2 back into num, throwing away the old value for num
o Now num is 2!
o It then saves that 22 back into num, throwing away the old value for num
It might feel weird to see the same variable on both sides of the equals sign, but I
promise you’ll get used to it! Just know that you’re overwriting the old num every time
you do num = ... - the old num disappears into dust, and you’ll never be able to get it
back! (Not that you’d want to)
Two common reasons to update a variable are counting things, or if you’re too lazy to
have separate variable names.
1. while expression:
2. statements
Here, the statements can be a single statement or a group of statements. The expression
should be any valid Python expression resulting in true or false. The true is any non-zero
value and false is 0.
While loop Flowchart
Example 1
1. i=1
2. while(i<=5):
3. print(i)
4. i=i+1
5. else:
6. print("The while loop exhausted")
Example 2
1. i=1
2. while(i<=5):
3. print(i)
4. i=i+1
5. if(i==3):
6. break
7. else:
8. print("The while loop exhausted")
var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num
Any non-zero value in the while loop indicates an always-true condition, whereas zero
indicates the always-false condition. This type of approach is useful if we want our program to
run continuously in the loop without any disturbance.
Example 1
1. while (1):
2. print("Hi! we are inside the infinite while loop")
Output:
Example 2
1. var = 1
2. while(var != 2):
3. i = int(input("Enter the number:"))
4. print("Entered value is %d"%(i))
Example:
Output:
Current Letter : j
Current Letter : v
Current Letter : p
Current Letter : o
Current Letter : i
Current Letter : n
2. Break Statement - When the break statement is encountered, it brings control out of
the loop.
Example:
Output:
Current Letter : j
Current Letter : a
Current Letter : v
Current Letter : a
3. Pass Statement - The pass statement is used to declare the empty loop. It is also
used to define empty class, function, and control statement. Let's understand the
following example.
Example -
1. # An empty loop
2. str1 = 'javatpoint'
3. i=0
4.
5. while i < len(str1):
6. i += 1
7. pass
8. print('Value of i :', i)
Output:
Value of i : 10
ntered value is 10
Infinite time
The break is commonly used in the cases where we need to break the loop for a given
condition.
#loop statements
1. break;
Example 1
1. list =[1,2,3,4]
2. count = 1;
3. for i in list:
4. if i == 4:
5. print("item matched")
6. count = count + 1;
7. break
8. print("found at",count,"location");
Output:
nOutput:
item matched
found at 2 location
ter the number:10ue is 10
EExample 2
1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);
Output:
p
y
t
h
nter the number:10
Entered value is 10
Enter the number:10
Entered value is 10
Infinite time
Syntax
1. #loop statements
2. continue
3. #the code to be skipped
Flow Diagram
Example 1
1. i=0
2. while(i < 10):
3. i = i+1
4. if(i == 5):
5. continue
6. print(i)
Output:
1
2
3
4
6
7
8
9
10
Observe the output of above code, the value 5 is skipped because we have provided
the if condition using with continue statement in while loop. When it matched with
the given condition then control transferred to the beginning of the while loop and it
skipped the value 5 from the code.
Example 2
1. str = "JavaTpoint"
2. for i in str:
3. if(i == 'T'):
4. continue
5. print(i)
Output:
J
a
v
a
p
o
i
n
t
Python Pass
In Python, the pass keyword is used to execute nothing; it means, when we don't want
to execute code, the pass can be used to execute empty. It is the same as the name
refers to. It just makes the control to pass by without executing any code. If we want to
bypass any code pass statement can be used.
It is beneficial when a statement is required syntactically, but we want we don't want to
execute or execute it later. The difference between the comments and pass is that,
comments are entirely ignored by the Python interpreter, where the pass statement is
not ignored.
Suppose we have a loop, and we do not want to execute right this moment, but we will
execute in the future. Here we can use the pass.
Example - 2:
1. for i in [1,2,3,4,5]:
2. if(i==4):
3. pass
4. print("This is pass block",i)
5. print(i)
Output:
1. 1
2. 2
3. 3
4. This is pass block 4
5. 4
6. 5
Output:
*
* *
* * *
* * * *
* * * * *
Output:
Python String
Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes. The computer does not understand the characters; internally, it
stores manipulated character as the combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python
strings are also called the collection of Unicode characters.
Syntax:
1. str = "Hi Python !"
Here, if we check the type of the variable str using a Python script
In Python, strings are treated as the sequence of characters, which means that Python
doesn't support the character data-type; instead, a single character written as 'p' is
treated as the string of length 1.
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
As shown in Python, the slice operator [] is used to access the individual characters of
the string. However, we can use the : (colon) operator in Python to access the substring
from the given string. Consider the following example.
Here, we must notice that the upper range given in the slice operator is always exclusive
i.e., if str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and
nothing else.
Example
# Python program to demonstrate
# string slicing
# String slicing
String ='ASTRING'
s1 = slice(3)
s2 = slice(1, 5, 2)
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
Output:
String slicing
AST
SR
GITA
Extending indexing
In Python, indexing syntax can be used as a substitute for the slice object. This
is an easy and convenient way to slice a string both syntax wise and execution
wise.
Syntax
string[start:end:step]
start, end and step have the same mechanism as slice() constructor.
Example
String ='ASTRING'
print(String[:3])
print(String[1:5:2])
print(String[-1:-12:-2])
print("\nReverse String")
print(String[::-1])
Output:
AST
SR
GITA
Reverse String
GNIRTSA
count = 0
for i in range(len(string)):
if(string[i] == char):
count = count + 1
print("The total Number of Times ", char, " has Occurred = " , count)
i=0
count = 0
if(string[i] == char):
count = count + 1
i=i+1
print("The total Number of Times ", char, " has Occurred = " , count)
>>>
total = 0
for i in range(len(str1)):
total = total + 1
total = 0
i=0
total = total + 1
i=i+1
Output:
String Length Using len() Method
Here,
Next, we directly call the method len() with the string and print the value returned
by it. As we can see, the method gives us the right length for the given string, str1.
list1= [1,2,3,4,5]
string1= "My name is AskPython"
tuple1=(11,22,33,44)
Here:
list1= [1,2,3,4,5]
string1= "My name is AskPython"
tuple1=(11,22,33,44)
Program
a = 10
b = 7
list = [1,2,3,4,5,6,7,8,9..)
If (a is in list):
print: line - 1 “a is presented in the list”
else
print: line - 1 “a is not presented in the list”
If (b is in list):
print: line - 2 “b is presented in the list”
else
print: line - 2 “b is not presented in the list”
When you are done with the execution of above program, you will get the below output:
“Not in” operator, the name itself is expressing the meaning that something is not inside. It
goes through a particular sequence to find weather a value is in the specified list or not. If it
finds there is no such value, it returns True, otherwise False.
Program
Run:
Python3
print("Geek" == "Geek")
print("Geek" != "Geek")
Output:
True
True
False
False
Method 2: Using is and is not
The == operator compares the values of both the operands and checks for
value equality. Whereas is operator checks whether both the operands refer to
the same object or not. The same is the case for != and is not.
Let us understand this with an example:
Python3
str1 = "Geek"
str2 = "Geek"
str3 = str1
print(str1 is str1)
print(str1 is str2)
print(str1 is str3)
str1 += "s"
str4 = "Geeks"
print(str1 is str4)
Output:
ID of str1 = 0x7f6037051570
ID of str2 = 0x7f6037051570
ID of str3 = 0x7f6037051570
True
True
True
ID of changed str1 = 0x7f60356137d8
ID of str4 = 0x7f60356137a0
False
The object ID of the strings may vary on different machines. The object IDs of
str1, str2 and str3 were the same therefore they the result is True in all the
cases. After the object id of str1 is changed, the result of str1 and str2 will be
false. Even after creating str4 with the same contents as in the new str1, the
answer will be false as their object IDs are different.
Vice-versa will happen with is not.
Method 3: Creating a user-defined function.
By using relational operators we can only compare the strings by their
unicodes. In order to compare two strings according to some other parameters,
we can make user-defined functions.
In the following code, our user-defined function will compare the strings based
upon the number of digits.
Python3
count1 = 0
count2 = 0
for i in range(len(str1)):
count1 += 1
for i in range(len(str2)):
count2 += 1
print(compare_strings("123", "12345"))
print(compare_strings("12345", "geeks"))
print(compare_strings("12geeks", "geeks12"))
Output:
False
False
True
Note: All string methods returns new values. They do not change the original string.
Method Description
endswith() Returns true if the string ends with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice
versa
The fundamental distinction that Python makes on data is whether or not the
value of an object changes. An object is mutable if the value can change; else,
the object is immutable.
The elements of a tuple can not be modified. If you try to assign a new value to one of the
elements in a tuple, an error is returned.
>>> t_var = (3,4,5) # a tuple
>>> t_var[0]= 8
>>> t_var
Dictionaries
The elements cannot be reversed, as the items in the dictionary are in the form
of key-value pairs
Let's store the ages of two people in a dictionary. The two people
are Gabby and Maelle. Gabby is 8 and Maelle is 5. Note the name Gabby is a string and the
age 8 is an integer.
>>> age_dict = {"Gabby": 8 , "Maelle": 5}
>>> type(age_dict)
dict
The values stored in a dictionary are called and assigned using the following syntax:
dict_name[key] = value
>>> age_dict = {"Gabby": 8 , "Maelle": 5}
>>> age_dict["Gabby"]
8
We can add a new person to our age_dict with the following command:
>>> age_dict = {"Gabby": 8 , "Maelle": 5}
>>> age_dict["Peter"]= 40
>>> age_dict
{'Gabby': 8, 'Maelle': 5, 'Peter': 40}
Items can be removed from dictionaries by calling the .pop() method. The dictionary key (and
that key's associated value) supplied to the .pop() method is removed from the dictionary.
>>> age_dict = {"Gabby": 8 , "Maelle": 5}
>>> age_dict.pop("Gabby")
>>> age_dict
{'Maelle': 5}
Tuples are compared position by position: the first item of the first tuple is compared to
the first item of the second tuple; if they are not equal, this is the result of the
comparison, else the second item is considered, then the third and so on.
example
>>> a = (1, 2, 3)
>>> b = (1, 2, 5)
>>> a < b
True
There is another type of comparison that takes into account similar and different
elements. This can be performed using sets. Sets will take the tuples and take only
unique values. Then you can perform a & operation that acts like intersection to get the
common objects from the tuples.
example
>>> a = (1, 2, 3, 4, 5)
>>> b = (9, 8, 7, 6, 5)
>>> set(a) & set(b)
{5}
example
You can also use set.intersection function to perform this operation.
>>> a = (1, 2, 3, 4, 5)
>>> b = (9, 8, 7, 6, 5)
>>> set(a).instersection(set(b))
set([5])
Let us have a look at the following snippet which compares two tuples
in numerous scenarios:
# comparing integers
print((10, 20) < (10, 25))
print((10, 20) == (10, 25))
print((10, 20) > (10, 25))
# comparing strings
print(('x', 'y') < ('x', 'z'))
# comparing list of tuples
print(([4, 5], [5, 6]) == ([4, 5], [5, 6]))
Output:
True
False
False
True
True
Consider that you have couple of tuples with different lengths. Let us
have a look at how this comparison works in the following snippet:
Output:
(10, 20, 30) < (10, 20, 30, 40) --> TRUE
print("tup1 is greater!")
else:
print("tup2 is greater!")
Output:
tup1 is greater!
print("tup1 is greater!")
else:
print("tup2 is greater!")
Output:
tup1 is greater!
TUPLE ASSIGNMENT
Example:
-It is useful to swap the values of two variables. With conventional
assignment statements, we have to use a temporary variable. For example,
to swap a and b:
Output:
(2, 3)
(3, 2)
>>>
-Tuple assignment solves this problem neatly:
(a, b) = (b, a)
Example:
-To split an email address in to user name and a domain
>>> mailid='[email protected]'
>>> name,domain=mailid.split('@')
>>> print name
god
print (domain)
abc.org
Packing and Unpacking
In packing, we place value into a new tuple while in unpacking we extract
those values back into variables.
x = ("Guru99", 20, "Education") # tuple packing
(company, emp, profile) = x # tuple unpacking
print(company)
print(emp)
print(profile)
Python Tuple
Tuples are identical to lists in all respects, except for the following
properties:
Creating a Tuple
Examples:
my_tuple = (); //Empty tuplemy_tuple = (‘hello’,)
//For creating tuples with a single element, add a trailing comma to indicate that it is a
tuple.my_tuple = (10, ‘cat’, 99.9, (11, 22, 33))
//Nested tuple with mixed data type
Various operations that you have learned and performed on lists such
as accessing elements, indexing and negative indexing, slicing, looping
through elements, tuple length, checking if an element exists, and
sorting are true for tuples as well.
Deleting a tuple
A tuple can be deleted completely using the del keyword. For example,
my_tuple = (‘cat’, ‘rat’, ‘fish’)
del my_tuple //my_tuple gets deleted completely.
Tuple Methods
Python has two built-in methods count() and index() that you can use
on tuples.
count() Method
index() Method
The index() method finds the first occurrence of the specified value. It
raises an exception if the value is not found. Here is the example,
my_tuple = (30, 55, 23, 99, 21, 55, 23, 55, 42, 61, 99, 21, 55)
x = my_tuple.index(23)
//Searches for the first occurrence of the value 23, and returns its position.
print(x)
Thus, you can use a tuple when you don’t want your data to be
modified. If the values in the collection are meant to remain constant
for the entire life of the program, using a tuple guards against
accidental modification.
Python Dictionaries
You can change the value of a specific element by referring to its key
name.
my_dict = {‘name’: ‘Alexa’, ‘age’: 20, ‘place’: ‘Canada’}
my_dict[‘place’] = ‘Australia’
When looping through a dictionary, the return values are the keys of
the dictionary.
my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
for x in my_dict:
print(x) //print all keys in the dictionary one by one
Output:
name
place
age
Output:
Mariam
London
20
You can use the items() method for looping through both keys and
values.
my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
for x, y in my_dict.items():
print(x, “:”, y)
Output:
place : London
name : Mariam
age : 20
Dictionary Length
(i) pop() — removes the element with the specified key name.
my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
my_dict.pop(‘age’) //Removes the element with the key ‘age’
print(my_dict)
Output:
{‘name’: ‘Mariam’, ‘place’: ‘London’}
(ii) del — removes the element with the specified key name.
my_dict = {‘name’: ‘Mariam’, ‘age’: 20, ‘place’: ‘London’}
del my_dict[‘age’]
print(my_dict)
Output:
{‘name’: ‘Mariam’, ‘place’: ‘London’}
d = {'a': [1,2],
'b': [2,3],
'c': [4,5]}
print(d)
Output:
sample_dict[key] = list()
sample_dict[key].extend(list_of_values)
return sample_dict
print(word_freq)
Output:
{'example': [1, 3, 4, 8, 10], 'for': [3, 10, 15, 7, 9], 'this': [5, 3, 7, 8, 1],
'tutorial': [2, 3, 5, 6, 11, 20, 21, 22], 'python': [10, 3, 9, 8, 12]}
s = [('rome', 1), ('paris', 2), ('newyork', 3), ('paris', 4), ('delhi', 1)]
d = defaultdict(list)
for k, v in s:
d[k].append(v)
sorted(d.items())
print(d)
Output:
defaultdict(<class 'list'>,
{'rome': [1],
'newyork': [3],
'delhi': [1]
})
s = [('rome', 1), ('paris', 2), ('newyork', 3), ('paris', 4), ('delhi', 1)]
data_dict = {}
for x in s:
data_dict.setdefault(x[0],[]).append(x[1])
print(data_dict)
Output:
Dictionary can return the list of tuples by calling items, where each tuple is a
key value pair.
a = {'x':100, 'y':200}
b = list(a.items())
print(b)
Here are the differences between List, Tuple, Set, and Dictionary in Python:
Basics A list is basically The tuples refer to The sets are an In Python, the
Parameters List Tuple Set Dictionary
Homogeneity A list refers to a A tuple also refers A set also refers A dictionary also
data structure of a to a data structure of to a data structure refers to a data
non-homogenous the non- of the non- structure of the
type that homogenous type homogenous non-homogenous
functions to store that functions to type, but it stores type that functions
various elements store various various elements to store key-value
in columns, elements in in a single row. pairs.
multiple rows, columns, multiple
and single rows. rows, and single
rows.
Duplicate It allows various It allows various It does not allow The keys are not at
elements duplicate duplicate elements. any duplicate all duplicated.
elements. elements.
Nested Among It can be utilized It can be utilized in It can be utilized It can be utilized in
All in a List. a Tuple. in a Set. a Dictionary.
Function for We can create a We can create a We can create a We can create a
Creation list using tuple using set using dictionary using
the list() function. the tuple() function. the set() function. the dict() function.
Python List
A list in Python is used to store the sequence of various types of data. Python lists are
mutable type its mean we can modify its element after it created. However, Python
consists of six data-types that are capable to store the sequences, but the most
common and reliable type is the list.
A list can be defined as a collection of values or items of different types. The items in the
list are separated with the comma (,) and enclosed with the square brackets [].
A list is a sequence
Like a string, a list is a sequence of values. In a string, the values are
characters; in a list, they can be any type. The values in list are
called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the
elements in square brackets (“[” and “]”):
The first example is a list of four integers. The second is a list of three strings.
The elements of a list don’t have to be the same type. The following list contains
a string, a float, an integer, and (lo!) another list:
A list that contains no elements is called an empty list; you can create one with
empty brackets, [].
empty = []
Traversing Lists
Lists are basically equal to arrays in other languages. However, they do
have the extra benefit of being dynamic in size. In Python, the list is a
kind of container in Data structures. It comes in use for storing
numerous data at the same time. Contrasting to sets, in Python, lists
are ordered and have a definite count. Moreover, there are various
ways for traversing lists in Python.
for i in list:
print(i)
Output:
10
Using For Loop and Range ()
If you wish to use the traditional for loop which iterates from number x
to number y.
length = len(list)
for i in range(length):
print(list[i])
Output:
10
length = len(list)
i = 0
print(list[i])
i += 1
Output:
10
Using List Comprehension
This one is possibly the most concrete way.
Output:
10
Using Enumerate()
If you wish to convert the list into an iterable list of tuples (or get the
index on the basis of a condition check, for instance, in linear search,
one might want to save the index of minimum element), one can use the
enumerate () function.
list = [1, 3, 5, 7, 9]
# Using enumerate()
for i, val in enumerate(list):
Output:
0 , 1
1 , 3
2 , 5
3 , 7
4 , 9
You can also use the second method for finding the index. However, the
first method cannot be used unless an extra variable is incremented
every iteration. Moreover, the fifth method gives a concise
representation of this indexing.
1. append()
The append() method is used to add elements at the end of the list. This method can
only add a single element at a time. To add multiple elements, the append() method
myList.append(4)
myList.append(5)
myList.append(6)
myList.append(i)
print(myList)
Output:
2. extend()
The extend() method is used to add more than one element at the end of the list.
Although it can add more than one element, unlike append(), it adds them at the end
Code:
myList.extend([4, 5, 6])
myList.append(i)
print(myList)
Output:
3. insert()
The insert() method can add an element at a given position in the list. Thus, unlike
append(), it can add elements at any position, but like append(), it can add only one
element at a time. This method takes two arguments. The first argument specifies the
Code:
myList.insert(3, 4)
myList.insert(4, 5)
myList.insert(5, 6)
print(myList)
Output:
4. remove()
The remove() method is used to remove an element from the list. In the case of
multiple occurrences of the same element, only the first occurrence is removed.
Code:
myList.insert(4, 'makes')
myList.insert(5, 'learning')
Output:
5. pop()
The method pop() can remove an element from any position in the list. The parameter
Code:
myList.pop(4)
myList.insert(4, 'makes')
myList.insert(5, 'learning')
Output:
6. slice
The slice operation is used to print a section of the list. The slice operation returns a
Code:
Output:
7. reverse()
The reverse() operation is used to reverse the elements of the list. This method
modifies the original list. To reverse a list without modifying the original one, we use
the slice operation with negative indices. Specifying negative indices iterates the list
Output:
8. len()
The len() method returns the length of the list, i.e. the number of elements in the list.
Code:
print(len(myList))
Output:
9. min() & max()
The min() method returns the minimum value in the list. The max() method returns
the maximum value in the list. Both the methods accept only homogeneous lists, i.e.
Code:
print(min(myList))
Output:
Code:
print(min([1, 2, 3]))
print(max([1, 2, 3]))
Output:
10. count()
The function count() returns the number of occurrences of a given element in the list.
Code:
print(myList.count(3))
Output:
11. concatenate
The concatenate operation is used to merge two lists and return a single list. The +
sign is used to perform the concatenation. Note that the individual lists are not
Code:
Output:
12. multiply
Python also allows multiplying the list n times. The resultant list is the original list
iterated n times.
Code:
print(myList*2)
Output:
13. index()
The index() method returns the position of the first occurrence of the given element. It
takes two optional parameters – the begin index and the end index. These parameters
define the start and end position of the search area on the list. When supplied, the
element is searched only in the sub-list bound by the begin and end indices. When not
Code:
2nd position
Output:
14. sort()
The sort method sorts the list in ascending order. This operation can only be
Code:
yourList = [4, 2, 6, 5, 0, 1]
yourList.sort()
print(yourList)
Output:
15. clear()
This function erases all the elements from the list and empties them.
Code:
myList.sort()
print(myList)
Output:
Basic List Operations
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
index() Returns the index of the first element with the specified value
Note: Python does not have built-in support for Arrays, but Python Lists can be
used instead.
# Python 3 code to
# remove an item from list
'Lily', 'Carnations']
del lst[1]
Output:
Original List is : [‘Iris’, ‘Orchids’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]
After deleting the item : [‘Iris’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]
Method 2: Using remove()
We can remove an item from the list by passing the value of the item to be deleted as the parameter to
remove() function.
# Python 3 code to
'Lily', 'Carnations']
# using remove()
lst.remove('Orchids')
Output:
Original List is : [‘Iris’, ‘Orchids’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]
After deleting the item : [‘Iris’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]
Method 3: Using pop()
pop() is also a method of list. We can remove the element at the specified index and get the value of
that element using pop().
# Python 3 code to
# using pop()
a = lst.pop(1)
Output –
Original List is : [‘Iris’, ‘Orchids’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]
Item popped : Orchids
After deleting the item : [‘Iris’, ‘Rose’, ‘Lavender’, ‘Lily’, ‘Carnations’]
Strings
Strings can be defined as sequential collections of characters. This means that
the individual characters that make up a string are in a particular order from left
to right.
Lists
A list is a sequential collection of Python data values, where each value is
identified by an index. The values that make up a list are called its elements.
Lists are similar to strings, which are ordered collections of characters, except
that the elements of a list can have any type and for any one list, the items can
be of different types.
There are several ways to create a new list. The simplest is to enclose the
elements in square brackets ( [ and ]).
The first example is a list of four integers. The second is a list of three strings.
As we said above, the elements of a list don’t have to be the same type. The
following list contains a string, a float, an integer, and another list.
The general approach you'll be using is the join() function, with a couple of
options to choose from. The function is invoked on a string denoting a
separator - and this separator will be added between all joined items.
The simplest way to join these into a single string is to just pass the list into
the join() function:
string = "".join(base_list)
print(string)
We've joined a few characters, denoting the amino-acids present at the start
of the sequence of a protein found in the E. coli bacteria!
M, K, V, N, L, I, L, F, S, L, L, V
If you do have to convert the elements, you can simply use a list
comprehension:
string = "".join(str(element) for element in base_list)
Each element in the list is now passed through the str() function, which
converts them to a string. You can substitute this with any other function,
including custom ones. For instancec, let's create a function that capitalizes
each element in the 'off chance' an element isn't capitalized as it should be:
base_list = ['m', 'K', 'V', 'N', 'L', 'I', 'L', 'f', 'S', 'L', 'L', 'V']
def capitalize_char(char):
return char.upper()
print(string)
Finally, for a more clean and easy way to pass elements through a function -
we can use map(). Generally, the map() function is used to map values of one
collection to another, typically using a different (or even reduced) format.
For instance, you could map each character to another list of booleans, where
each boolean represents if the character is uppercase or not.
Of course, you can also always do a 1-to-1 mapping using the map() function
and, well, just map a string to a string, joining them together into a single one:
base_list = ['M', 'K', 'V', 'N', 'L', 'I', 'L', 'F', 'S', 'L', 'L', 'V']
print(string)
Parsing Lines:
Python provides inbuilt functions for creating, writing, and reading files. There
are two types of files that can be handled in python, normal text files and binary
files (written in binary language, 0s, and 1s).
Using readlines()
readlines() is used to read all the lines at a single go and then return them as
each line a string element in a list. This function can be used for small files, as it
reads the whole file content to the memory, then split it into separate lines. We
can iterate over the list and strip the newline ‘\n’ character using strip() function.
Example:
Python3
# Python code to
# demonstrate readlines()
# writing to file
file1.writelines(L)
file1.close()
# Using readlines()
count = 0
count += 1
Output:
Line1: Geeks
Line2: for
Line3: Geeks
Using readline()
readline() function reads a line of the file and return it in the form of the string. It
takes a parameter n, which specifies the maximum number of bytes that will be
read. However, does not reads more than one line, even if n exceeds the length
of the line. It will be efficient when reading a large file because instead of
fetching all the data in one go, it fetches line by line. readline() returns the next
line of the file which contains a newline character in the end. Also, if the end of
the file is reached, it will return an empty string.
Example:
Python3
# Python program to
# demonstrate readline()
# Writing to a file
file1.writelines((L))
file1.close()
# Using readline()
count = 0
while True:
count += 1
line = file1.readline()
# if line is empty
if not line:
break
file1.close()
Output:
Line1 Geeks
Line2 for
Line3 Geeks
Example:
Python3
# Python program to
# demonstrate reading files
# Writing to file
file1.writelines(L)
file1.close()
# Opening file
count = 0
count += 1
print("Line{}: {}".format(count, line.strip()))
# Closing files
file1.close()
Output:
With statement
In the above approaches, every time the file is opened it is needed to be closed
explicitly. If one forgets to close the file, it may introduce several bugs in the
code, i.e. many changes in files do not go into effect until the file is properly
closed. To prevent this with statement can be used. The With statement in
Python is used in exception handling to make the code cleaner and much more
readable. It simplifies the management of common resources like file streams.
Observe the following code example on how the use of with statement makes
the code cleaner. There is no need to call file.close() when using with the
statement. The with the statement itself ensures proper acquisition and release
of resources.
Example:
Python3
# Python program to
# demonstrate with
# statement
# Writing to file
fp.writelines(L)
# using readlines()
count = 0
print("Using readlines()")
Lines = fp.readlines()
count += 1
print("Line{}: {}".format(count, line.strip()))
# Using readline()
count = 0
print("\nUsing readline()")
while True:
count += 1
line = fp.readline()
if not line:
break
count += 1
Output:
Using readlines()
Line1: Geeks
Line2: for
Line3: Geeks
Using readline()
Line1: Geeks
Line2: for
Line3: Geeks
first_variable = "PYTHON"
print("Value of first:", first_variable)
print("Reference of first:", id(first_variable))
print("--------------")
Passing a list into a function allows that function to read and manipulate the list.
sample_list = [0, 1]
append_to_list(sample_list, 2)
print(sample_list)
OUTPUT
[0, 1, 2]