PYTHON Unit 1
PYTHON Unit 1
-----------------------------------------------------------------------------------------------------------------
Introduction- Conditional Statements – Looping and Control statements – String
Manipulation – Lists – Tuples – Dictionaries
Table of Contents
INTRODUCTION TO PYTHON
-----------------------------------------------------------------------------------------------------------------
Python is included in the default installation of Enterprise Linux.
It was mainly developed for emphasis on code readabil ity, and its syntax
allows programmers to express concepts in fewer lines of code.
A programming language with strong similarities to PERL, but with powerful
typing and object oriented features.
Commonly used for producing HTML content on websites. Grea t for text
files.
Useful built-in types (Tuples, lists, dictionaries).
Databases: Python provides interfaces to all major commercial databases.
Clean syntax, powerful extensions.
It can be used as a scripting language or can be compiled to byte -code for
building large applications.
Very high-level dynamic data types and supports dynamic type checking.
Supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA and Java.
There are two major Python versions- Python 2 and Python 3. Both are quite
different.
Finding an Interpreter
Windows:There are many interpreters available freely to run Python scripts like
IDLE ( Integrated Development Environment ) which is installed when you install
the python software from http://python.org/
Important differences between Python 2.x and Python 3.x with examples
Division operator
print function
Unicode
xrange
Error Handling
_future_ module
Python 2.x Python 3.x
Division Integer division given Integer division given
Operator rounded output exact output
print 7 / 5 gives 1 print 7 / 5 gives 1.4
instead of 1.4
Print Uses the syntax print Uses the syntax print()
Unicode Python 2 uses ASCII Python 3 uses Unicode
format code
-----------------------------------------------------------------------------------------------------------------
xrange It is supported It is supported in the for x in
format of range() range(1, 5):
print(x)
_future_module
The idea of
__future__
module is to help
in migration.
_future_module:
This is basically not a difference between two version, but u seful thing to mention
here. The idea of __future__ module is to help in migration. We can use Python 3.x
If we are planning Python 3.x support in our 2.x code,we can ise _future_ imports it
in our code.
For example, in below Python 2.x code, we use Python 3.x’s integer division
behavior using __future__ module
# In below python 2.x code, division works
# same as Python 3.x because we use __future__
from __future__ import division
print 7 / 5
print -7 / 5
Output :
1.4
-1.4
Another example where we use brackets in Python 2.x using __future__ module
from __future__ import print_function
print('GeeksforGeeks')
Unicode
Unicode is an entirely new idea in setting up binary codes for text or script characters.
-----------------------------------------------------------------------------------------------------------------
Before Unicode was invented, there were hundreds of different encoding systems for
assigning these numbers. No single encoding could contain enough characters.
Unicode provides a unique number for every character and so you do not have this
problem if you use Unicode
Currently, the Unicode standard contains 34,168 distinct coded characters derived
from 24 supported language scripts. These characters cover the principal written
languages of the world.
Python Keywords
Keywords are the reserved words in Python.
A keyword cannot be used as a variable name, function name or any other
identifier.
They are used to define the syntax and structure of the Python language.
In Python, keywords are case sensitive.
There are 33 keywords in Python 3.3.
Python Identifiers
Identifier is the name given to entities like class, functions, vari ables etc. in Python.
It helps differentiating one entity from another.
-----------------------------------------------------------------------------------------------------------------
Python Statement
Instructions that a Python interpreter can execute are called statements.
For example, a = 1 is an assignment statement. if statement, for statement, while
statement etc. are other kinds of statements in Python.
Multi-line statement
In Python, end of a statement is marked by a newline character. But a statement can
be extended over multiple lines with the line continuation character (\).
Example
a=1+2+3+\
4+5+6+\
7+8+9
print(a)
Output = 45
a = 1; b = 2; c = 3
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a
block of code. Python uses indentation.
Indentation can be ignored in line continuation. But it's a good idea to always indent.
It makes the code more readable.
Incorrect indentation will result into IndentationError.
if True:
print('Hello')
a=5
-----------------------------------------------------------------------------------------------------------------
and
if True: print('Hello'); a = 5
Python Comments
Comments are used for better understanding of a program. Python Interpreter ignores
comment.
Single Line comment si represented by #
Multiple Line comment is represented by triple quotes, either ''' or """.
Example
"""This is also a
perfect example of
multi-line comments"""
Variable
Variable is a named location used to store data in the memory. Each variable must
have a unique name called Identifier. Variables acts as a container that hold data
which can be changed later throughout programming.
OUTPUT
>>> a=10
>>> b=10.5
>>> name="python"
>>> print(a,b,name)
10 10.5 python
-----------------------------------------------------------------------------------------------------------------
A window will be opened. Type the python commands one by one and save it with
the extension .py. Run the program by pressing F5
Constants
A constant is a type of variable whose value cannot be changed.
Assigning value to a constant in Python
In Python, constants are usually declared and assign ed on a module. Here, the
module means a new file containing variables, functions etc which is imported to
main file. Inside the module, constants are written in all capital letters and
underscores separating the words.
Create a file called as constants.py
PI = 3.14
GRAVITY = 9.8
-----------------------------------------------------------------------------------------------------------------
Save as constant.py
Invoke the constants created in an another file using the import command
import constant
print(constant.PI)
print(constant.GRAVITY)
Literals
Numeric Literals
Numeric Literals are immutable. Numeric literals can belong to following four
different numerical types.
Int(signed Long(long float(floating
Complex(complex)
integers) integers) point)
Integers of
Numbers( can be
unlimited size Real numbers In the form of a+bj where a
both positive and
followed by with both integer forms the real part and b
negative) with no
lowercase or and fractional part forms the imaginary part of
fractional
uppercase L eg: eg: -26.2 complex number. eg: 3.14j
part.eg: 100
87032845L
Program No : 1
a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal
#Float Literal
float_1 = 10.5
float_2 = 1.5e2
#Complex Literal
Output No : 1
10 100 200 300
-----------------------------------------------------------------------------------------------------------------
10.5 150.0
(2+3.14j) 3.14 2.0
Explanation
When the variables are printed all are converted into decimal values.
x.imag and x.real are used to extract the real and imaginary values from the complex
number.
String literals
A string literal is a sequence of characters surrounded by quotes. Strings can be
represented by single, double or triple quotes.
A character literal is a single character surrounded by single or double quotes.
Single line String- Strings that are terminated within a single line are known as
Single line Strings.
Multi line String- A piece of text that is spread along multiple lines is known as
Multiple line String.
There are two ways to create Multiline Strings:
1). Adding black slash at the end of each line.
2) Using triple quotation marks:-
Program No : 2
print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)
print (str2)
print(text1)
Output No : 2
-----------------------------------------------------------------------------------------------------------------
This is Python
C
This is a multiline string with more than one line code.
Ünicöde
raw \n string
welcome
to
SSSIT
hellouser
Boolean literals
A Boolean literal can have any of the two values: True or False .
Program No : 3
x = (1 == True)
y = (0 == False)
a = True + 4
b = False + 10
print("x is", x)
print("y is", y)
print("a:", a)
print("b:", b)
Output No : 3
x is True
y is True
a: 5
b: 10
Explanation
In Python there are only 2 Boolean values called as True and false. True represents 1
and False Represents 0
None is used to specify to that field that is not created. It is also used for end of lists
in Python.
-----------------------------------------------------------------------------------------------------------------
val1=10
val2=None
print(val1)
print (val2)
Eg:
====== RESTART: C:/Users/MCA/AppData/Local/Programs/samples/special.py
10
None
Python Operators
Operators are particular symbols that are used to perform operations on operands. It
returns result that can be used in application.
Types of Operators
Python supports the following operators
1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Membership Operators.
6. Identity Operators.
7. Bitwise Operators.
Arithmetic Operators
The following table contains the arithmetic operators that are used to perform
arithmetic operations.
Operators Description
// Perform Floor division(gives integer value after division)
+ To perform addition
- To perform subtraction
* To perform multiplication
/ To perform division
% To return remainder after division(Modulus)
** Perform exponent(raise to power)
Relational Operators
The following table contains the relational operators that are used to check relations.
Operators Description
< Less than
> Greater than
-----------------------------------------------------------------------------------------------------------------
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
<> Not equal to(similar to !=)
Assignment Operators
The following table contains the assignment operators that are used to assign values
to the variables.
Operators Description
= Assignment
/= Divide and Assign
+= Add and assign
-= Subtract and Assign
*= Multiply and assign
%= Modulus and assign
**= Exponent and assign
//= Floor division and assign
Logical Operators
The following table contains the arithmetic operators that are used to perform
arithmetic operations.
Operators Description
and Logical AND(When both conditions are true output will be true)
or Logical OR (If any one condition is true output will be true)
not Logical NOT(Compliment the condition i.e., reverse)
Membership Operators
The following table contains the membership operators.
Operators Description
in Returns true if a variable is in sequence of another variable, else false.
not in Returns true if a variable is not in sequence of another variable, else false.
Program No : 4
a=10
b=20
list=[10,20,30,40,50];
if (a in list):
-----------------------------------------------------------------------------------------------------------------
print ("a is in given list" )
else:
print ("a is not in given list")
if(b not in list):
print ("b is not given in list")
else:
print ("b is given in list")
Output No : 4
a is in given list
b is given in list
Identity Operators
The following table contains the identity operators.
Operators Description
is Returns true if identity of two operands are same, else false
is not Returns true if identity of two operands are not same, else false.
Program No : 5
a=20
b=20
if( a is b):
print ("a,b have same identity ")
else:
print ("a, b are different ")
b=10
if( a is not b):
print ("a,b have different identity ")
else:
print ("a,b have same identity")
Output No : 5
-----------------------------------------------------------------------------------------------------------------
Python Tuple
Python Strings
Python Set
Python Numbers
Integers, Floating point numbers and complex numbers falls under Python numbers
category. They are defined as int ,float and complex class in Python.
Program No : 6
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
print(isinstance(1+4j,complex))
Output No : 6
C:/Users/MCA/AppData/Local/Programs/Python/sample programs/num.py =
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True
True
Python List
List is an ordered sequence of items.
It is one of the most used datatype in Python and is very Flexible.
-----------------------------------------------------------------------------------------------------------------
All the items in a list do not need to be of the same type.
List is a collection of Heterogenous data types
The slicing operator [ ] can be used to extract an item or a range of items from
a list. Index starts form 0 in Python.
Lists are mutable, meaning, value of elements of a list can be altered
Declaration of List
<list_name>=[value1,value2,value3,...,valuen];
a = [1, 2.2, 'python']
Accessing a List
<list_name>[index]
Program No : 7
Output No : 7
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/list1.py
[5, 'program', (1+3j)]
[5, 'program', 'hello']
Python Tuple
Tuple is an ordered sequence of items same as list.
The only difference is that tuples are immutable.
Tuples once created cannot be modified
Tuples are used to write-protect data and are usually faster than list as it
cannot change dynamically.
It is defined within parentheses () where items are separated by commas.
Program No : 8
t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])
# t[0:3] = (5, 'program', (1+3j))
print("t[0:3] = ", t[0:3])
# generates error since it does not support assignment
-----------------------------------------------------------------------------------------------------------------
t[0] = 100
print(t[0])
Output No : 8
t[1] = program
t[0:3] = (5, 'program', (1+3j))
Python Strings
String is sequence of Unicode characters.
Single quotes or double quotes are used to represent strings.
Multi-line strings can be denoted using triple quotes, ''' or """
Strings are immutable in Python
Program No : 9
s = 'Hello world!'
print("s[4] = ", s[4])
print("s[6:11] = ", s[6:11])
# Generates error
# Strings are immutable in Python
s[5] ='d'
Output No : 9
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/string.py
s[4] = o
s[6:11] = world
-----------------------------------------------------------------------------------------------------------------
Set is defined by values separated by comma inside braces { }.
Items in a set are not ordered.
We can perform set operations like union, intersection on two sets. Set have unique
values. They eliminate duplicates.
Since, set are unordered collection, indexing has no meaning. Hence the sli cing
operator [] does not work.
Program No : 10
a = {5,2,3,1,4}
print("a = ", a)
print(type(a))
print(a[0])
Output No : 10
= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/set.py =
a = {1, 2, 3, 4, 5}
<class 'set'>
Python Dictionary
Program No : 11
d = {1:'value','key':2}
print(type(d))
print("d[1] = ", d[1]);
print("d['key'] = ", d['key']);
-----------------------------------------------------------------------------------------------------------------
# Generates error
#print("d[2] = ", d[2]);
Output No : 11
= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/dict.py =
<class 'dict'>
d[1] = value
d['key'] = 2
CONDITIONAL STATEMENTS
Output No : 12
-----------------------------------------------------------------------------------------------------------------
= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/if.py =
Enter the Age : 21
Eligible to Vote
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test
expression and will execute body of if
only when test condition is True .
If the condition is False , body of else is
executed. Indentation is used to separate
the blocks.
Program No : 13
Output No : 13
Eligible to Vote
if test expression:
Body of if
-----------------------------------------------------------------------------------------------------------------
elif test expression:
Body of elif
Output No : 14
= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/if.py =
Enter the Number1
Number is positive
= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/if.py =
Enter the Number0
Number is Zero
-----------------------------------------------------------------------------------------------------------------
= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/if.py =
Enter the Number-34
Number is Negative
Looping statements are used for executing a set of statements for a pr edefined times.
Types of Loop
For Loop
While Loop
For Loop
Python for loop is used to iterate the elements of a collection in the order that they
appear. This collection can be a sequence(list or string). Loop continues until we
reach the last item in the sequence.
Program No : 15
-----------------------------------------------------------------------------------------------------------------
Output No : 15
Program No : 16
Output No : 16
= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/for.py =
Enter the value of N : 5
The sum is 10
Program No : 17
Output No : 17
= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/for.py =
Enter the value of N : 10
-----------------------------------------------------------------------------------------------------------------
7
9
Program No : 18
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Output No : 18
= RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/for.py =
0
1
5
No items left.
While Loop
The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
-----------------------------------------------------------------------------------------------------------------
In while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True. After one iteration, the test expression is
checked again. This process continues until the test_expression evaluates to False .
Program No : 19
Output No : 19
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/while.py
Enter n: 10
Same as that of for loop, we can have an optional else block with while loop as well.
The else part is executed if the condition in the while loop evaluates to False . The
while loop can be terminated with a
break statement.
-----------------------------------------------------------------------------------------------------------------
Program No : 20
Output No : 20
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/while.py
Enter n: 5
In Python, break and continue statements can alter the flow of a normal loop.
Loops iterate over a block of code until test expression is false, but sometimes to
terminate the current iteration or even the whole loop without check ing test
expression break and continue statements are used.
-----------------------------------------------------------------------------------------------------------------
Program No : 21
for i in [1,2,3,4,5]:
if i==4:
print ("Element found")
break
print (i)
Output No : 21
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/continue.py
Element found
4
Continue Statement
It returns the control to the beginning of the while loop.. The continue statement
rejects all the remaining statements in the current iteration of the loop and moves the
control back to the top of the loop.
The continue statement can be used in both while and for loops.
Syntax
continue
Flow Diagram
-----------------------------------------------------------------------------------------------------------------
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Example
STRING MANIPULATION
-----------------------------------------------------------------------------------------------------------------
Concatenation of strings are created using + operator
String Creation
Strings can be created by enclosing characters inside a single quote or double quotes
Example
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
Accessing Strings:
In Python, Strings are stored as individual characters in a contiguous memory
location.
The benefit of using String is that it can be accessed from both the directions
in forward and backward.
Both forward as well as backward indexing are provided using Strings in
Python.
o Forward indexing starts with 0,1,2,3,....
o Backward indexing starts with -1,-2,-3,-4,....
-----------------------------------------------------------------------------------------------------------------
Program No : 22
print( "Hi Mr Ram.")
# use of escape sequence
print ("He said, \"Welcome to the Show\"")
print ('Hey so happy to be here')
# use of mix quotes
print ('Getting Excited, "Loving it"' )
Output No : 22
Hi Mr Ram.
He said, "Welcome to the Show"
Hey so happy to be here
Getting Excited, "Loving it"
Program No : 23
Simple program to retrieve String in reverse as well as normal form.
name="MCA"
length=len(name)
i=0
for n in range(-1,(-length-1),-1):
print (name[i],"\t",name[n])
i= i+1
Output No : 23
C:/Users/MCA/AppData/Local/Programs/Python/sample programs/str1.py
M A
C C
A M
Strings Operators
There are basically 3 types of Operators supported by String:
1. Basic Operators.
2. Membership Operators.
3. Relational Operators.
https://py3.codeskulptor.org/#user305_tw0W4ofIHP_0.py
Basic Operators:
There are two types of basic operators in String. They are "+" and
"*".
String Concatenation Operator :(+)
The concatenation operator (+) concatenate two Strings and forms a new String
-----------------------------------------------------------------------------------------------------------------
Membership Operators
Membership Operators are already discussed in the Operators section. Let see
with context of String.
There are two types of Membership operators:
o in:"in" operator return true if a character or the entire substring is
present in the specified string, otherwise false.
o not in:"not in" operator return true if a character or entire substring
does not exist in the specified string, otherwise false.
Program No : 24
str1="javatpoint"
str2='sssit'
str3="seomount"
str4='java'
-----------------------------------------------------------------------------------------------------------------
st5="it"
str6="seo"
print(str4 in str1)
print(st5 in str2)
print(str6 in str3)
print(str4 not in str1)
print(str1 not in str4)
Output No : 24
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/str1.py
True
True
True
False
True
Relational Operators:
All the comparison operators i.e., (<,><=,>=,==,!=,<>) are also applicable to strings.
The Strings are compared based on the ASCII value or Unicode(i.e., dictionary
Order).
Eg:
>>> "RAJAT"=="RAJAT"
True
>>> "afsha">='Afsha'
True
>>> "Z"<>"z"
True
Slice Notation:
String slice can be defined as substring which is the part of string. Therefore further
substring can be obtained from a string.
There can be many forms to slice a string. As string can be accessed or indexed from
both the direction and hence string can also be sliced from both the direction tha t is
left and right.
Syntax:
<string_name>[startIndex:endIndex:Stepvalue],
<string_name>[:endIndex],
<string_name>[startIndex:]
Program No : 25
-----------------------------------------------------------------------------------------------------------------
str="Nikhil"
str[0:6]
print(str[0:3])
print(str[2:5])
print(str[:6])
print(str[3:])
Output No : 25
Nik
khi
Nikhil
Hil
a="raja"
a="ram"
print(a)
del a
print(a)
-----------------------------------------------------------------------------------------------------------------
But we can combine strings and numbers by using the format() method!
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
O/P
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
O/P
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
str="Welcome to SSSIT"; 3
substr1="come"; 8
substr2="to"; 3
print (str.index(substr1) ) ; Traceback (most recent
print (str.index(substr2)); call last):
print (str.index(substr1,3,10)); File
print (str.index(substr2,15)); "C:/Users/Nirmalaa/Ap
Same as find() except it raises an
index(substring, beginIndex, pData/Local/Programs/
exception if string is not found. If
endIndex) Python/Python36-
index option fails it raises an error
32/sample
programs/string1.py",
line 7, in <module>
print
(str.index(substr2,12));
ValueError: substring
not found
It returns True if characters in the str="Welcome to sssit"; False
string are alphanumeric i.e., print (str.isalnum()); True
isalnum() alphabets or numbers and there is str1="Python47";
at least 1 character. Otherwise it print (str1.isalnum());
returns False.
string1="HelloPython"; # Even True
It returns True when all the
space is not allowed False
characters are alphabets and there
isalpha() print (string1.isalpha());
is at least one character, otherwise
string2="This is Python2.7.4"
False.
print (string2.isalpha())
isdigit() It returns True if all the characters string1="HelloPython"; False
-----------------------------------------------------------------------------------------------------------------
are digit and there is at least one print (string1.isdigit()) True
character, otherwise False. string2="98564738"
print (string2.isdigit())
string1="Hello Python"; False
It returns True if the characters of print(string1.islower()) True
islower() a string are in lower case, string2="welcome to "
otherwise False. print (string2.islower())
string1=" "; 4
print (len(string1)); 16
len(string) len() returns the length of a string. string2="WELCOME TO SSSIT"
print (len(string2));
-----------------------------------------------------------------------------------------------------------------
print (string2.lower());
-----------------------------------------------------------------------------------------------------------------
Remove all trailing & leading string1=" Hello Python "; Hello Python
whitespace of a string. It can also print (string1.strip()); @welcome to SSSIT
strip()
be used to remove particular
character from trailing.
-----------------------------------------------------------------------------------------------------------------
The constants defined in this module are:
string.ascii_letters
The concatenation of the ascii_lowercase and ascii_uppercase constants
described below. This value is not locale-dependent.
string.ascii_lowercase
The lowercase letters 'abcdefghijklmnopqrstuvwxyz'. This value is not locale -
dependent and will not change.
string.ascii_uppercase
The uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. This value is
not locale-dependent and will not change.
string.digits
The string '0123456789'.
string.hexdigits
The string '0123456789abcdefABCDEF'.
string.octdigits
The string '01234567'.
string.punctuation
String of ASCII characters which are considered punctuation characters in the
C locale.
string.printable
String of ASCII characters which are considered printable. This is a
combination of digits, ascii_letters, punctuation, and whitespace.
string.whitespace
A string containing all ASCII characters that are considered whitespace. This
includes the characters space, tab, linefeed, return, formfeed, and vertical tab.
LISTS
Python lists are the data structure that is capable of holding different type of data.
Python lists are mutable i.e., Python will not create a new list if we modify an
element in the list.
It is a container that holds other objects in a given order.
Different operation like insertion and deletion can be performed on lists.
A list can be composed by storing a sequence of different type of values separated
by commas.
A python list is enclosed between square([]) brackets and each item is separated
by a comma.
The elements are stored in the index basis with starting index as 0.
eg:
1. data1=[1,2,3,4];
2. data2=['x','y','z'];
3. data3=[12.5,11.6];
-----------------------------------------------------------------------------------------------------------------
4. data4=['raman','rahul'];
5. data5=[];
6. data6=['abhinav',10,56.4,'a'];
Program No : 26
# Creation of List
L = ['yellow', 'red', 'blue', 'green', 'black']
print (L)
# Accessing or Indexing
print (L[0])
#Slicing
print(L[1:4])
print(L[2:])
print(L[:2])
print(L[-1])
print(L[1:-1])
#Remove - remove first item in list with value "white" based on value
L.remove("White")
-----------------------------------------------------------------------------------------------------------------
print(L)
# Remove an item from a list given its index instead of its value
del L[0]
print(L)
Output No : 26
RESTART: C:/Users/MCA/AppData/Local/Programs/Python/sample
programs/list2.py
['yellow', 'red', 'blue', 'green', 'black']
yellow
['red', 'blue', 'green']
['blue', 'green', 'black']
['yellow', 'red']
black
['red', 'blue', 'green']
5
['black', 'blue', 'green', 'red', 'yellow']
['yellow', 'red', 'blue', 'green', 'black', 'Pink']
['yellow', 'red', 'blue', 'green', 'White', 'black', 'Pink']
['yellow', 'red', 'blue', 'green', 'White', 'black', 'Pink', 'purple', 'grey', 'violet']
['yellow', 'red', 'blue', 'green', 'black', 'Pink', 'purple', 'grey', 'violet']
['red', 'blue', 'green', 'black', 'Pink', 'purple', 'grey', 'violet']
['red', 'blue', 'green', 'black', 'Pink', 'purple', 'grey']
['red', 'green', 'black', 'Pink', 'purple', 'grey']
['grey', 'purple', 'Pink', 'black', 'green', 'red']
-----------------------------------------------------------------------------------------------------------------
Program No : 27
Write a Python program to check whether a list contains a sublist.
LL=[]
SL=[]
N = int(input("Enter the Number of elements in List :"))
for i in range(0,N):
item = int(input("Enter Elements for List :"))
LL.append(item)
sub_set = False
if SL == []:
sub_set = True
elif SL == LL:
sub_set = True
elif len(SL) > len(LL):
sub_set = False
else:
for i in range(len(LL)):
if LL[i] == SL[0]:
n=1
while (n < len(SL)) and (LL[i+n] == SL[n]):
n += 1
if n == len(SL):
sub_set = True
print(sub_set)
Output No : 27
-----------------------------------------------------------------------------------------------------------------
Enter Elements for List :3
Enter Elements for List :4
Enter Elements for List :5
Enter Elements for List :6
Enter the Number of elements in sublist :3
Enter Elements for List :1
Enter Elements for List :2
Enter Elements for List :3
[1, 2, 3, 4, 5, 6]
[1, 2, 3]
True
>>>
RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -
32/sample programs/list2.py
Enter the Number of elements in List :5
Enter Elements for List :1
Enter Elements for List :2
Enter Elements for List :3
Enter Elements for List :4
Enter Elements for List :5
Enter the Number of elements in sublist :3
Enter Elements for List :6
Enter Elements for List :7
Enter Elements for List :8
[1, 2, 3, 4, 5]
[6, 7, 8]
False
Program No : 28
LL=[]
N = int(input("Enter the Number of elements in List :"))
for i in range(0,N):
item = int(input("Enter Elements for List :"))
LL.append(item)
min = int(input("Enter the Minimum Range Value :"))
max = int(input("Enter the Maximum Range Value :"))
ctr = 0
for x in LL:
if min <= x <= max:
-----------------------------------------------------------------------------------------------------------------
ctr += 1
print(" Count of Elements between the range ",min, "and" ,max ,"=",ctr)
Output No : 28
Program No : 29
import itertools
print(list(itertools.permutations([1,2,3])))
Output No : 29
RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -32/sample
programs/list3.py
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
TUPLES
A Tuple is a collection of immutable Python objects separated by commas.
The difference between the two is that we cannot change the elements of a tuple once
it is assigned whereas in a list, elements can b e changed.
-----------------------------------------------------------------------------------------------------------------
Tuple are generally used for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.
Since tuple are immutable, iterating through tuple is faster than with list. So
there is a slight performance boost.
Tuples that contain immutable elements can be used as key for a dictionary.
With list, this is not possible.
Tuple will guarantee that it remains write-protected.
Creating a Tuple
A tuple can have any number of items and they may be of different types (integer,
float, list, string etc.).
-----------------------------------------------------------------------------------------------------------------
(*)
Immutable Tuples tuple1 = (0, 1, 2, 3) Traceback (most
#code to test tuple1[0] = 4 recent call last):
that tuples are print(tuple1) File
immutable "C:/Users/MCA/AppD
ata/Local/Programs/P
ython/sample
programs/tuple1.py",
line 5, in <module>
tuple1[0] = 4
TypeError: 'tuple'
object does not
support item
assignment
Slicing a=(1,2,3,4,5,6,7,8) (2, 3, 4)
The slice object initialization # starts from initial index value 1 (2, 4)
takes in 3 arguments with the and ends with final index value - 1 (8, 7, 6, 5, 4, 3, 2, 1)
last one being the optional print(a[1:4]) (8, 6, 4, 2)
index increment. The general #last colon mentions the slicing [2, 3]
method format is: slice(start, increment
stop, increment), and it is #By default, Python sets this
analogous to increment to 1, but that extra colon
start:stop:increment when at the end of the numbers allows us
applied to a list or tuple. to specify the slicing increment
print(a[1:4:2])
#reverse print
print(a[::-1])
#reverse with slicing increment
print(a[::-2])
#using slice
a = [1, 2, 3, 4, 5]
sliceObj = slice(1, 3)
print(a[sliceObj])
In order to delete a tuple, the tuple3 = ( 0, 1) NameError: name
del keyword is used del tuple3 'tuple3' is not defined
print(tuple3)
Built in Tuple Functions
Finding Length of a Tuple tuple2 = ('python', 'program') 2
print(len(tuple2))
Converting a list to a tuple # Code for converting a list and a (0, 1, 2)
string into a tuple ('p', 'y', 't', 'h', 'o', 'n')
-----------------------------------------------------------------------------------------------------------------
list1 = [0, 1, 2]
print(tuple(list1))
print(tuple('python')) # string
'python'
Using cmp(), max() , min() Maximum element in
tuple1 = ('python', 'good') tuples 1 = python
tuple2 = (4,6,7,1) Maximum element in
tuples 2 = 7
print ('Maximum element in tuples Minimum element in
1 = ' +str(max(tuple1))) tuples 1 = good
print ('Maximum element in tuples Minimum element in
2 = ' +str(max(tuple2))) tuples 2 = 1
Program No : 30
1. Create a tuple named as TUPLE1 with the following items in the tuple
a. TUPLE1 = (‘tupleexample', False, 3.2, 1)
b. TUPLE2 = tuplex = ("p", "y", "t", "h", "o", "n", "c", "o",“d”,"e")
2. Display the TUPLE1, TUPLE2
3. Display the 4th Item from the TUPLE2
4. Display the 4th Item from TUPLE2 using Negative Indexing
5. Check whether the element 3.2 exist in TUPLE1
6. Convert the List1 = [1,2,3,4,5,6] to a Tuple
7. Unpack the TUPLE3 = 4,8,3 into Several variables
8. Count the frequency of the Item “o” from the TUPLE2
9. Display the length of the TUPLE2
10. Reverse the TUPLE2
'''Create a tuple named as TUPLE1 with the following items in the tuple
-----------------------------------------------------------------------------------------------------------------
a. TUPLE1 = (‘tupleexample', False, 3.2, 1)
b. TUPLE2 = tuplex = ("p", "y", "t", "h", "o", "n", "c", "o",“d”,"e") '''
print(tuplex)
Output No : 30
-----------------------------------------------------------------------------------------------------------------
Program No : 31
Write a program in python to add and remove and item from tuple.
tuplex = (4, 6, 2, 8, 3, 1)
print(tuplex)
#direct addiotn of value into a tuple through append or insert is not possible
# no direct methods of insert or append.
#tuplex.append(100)
#tuples are immutable, so you can not add new elements
#using merge of tuples with the + operator you can add an element and it will create
a new tuple
tuplex = tuplex + (9,)
print(tuplex)
#adding items in a specific index
tuplex = tuplex[:5] + (15, 20, 25) + tuplex[5:]
print(tuplex)
#converting the tuple to list
listx = list(tuplex)
#use different ways to add items in list
listx.append(30)
tuplex = tuple(listx)
print(tuplex)
-----------------------------------------------------------------------------------------------------------------
tuplex = tuple(listx)
print(tuplex)
Output No : 31
(4, 6, 2, 8, 3, 1)
(4, 6, 2, 8, 3, 1, 9)
(4, 6, 2, 8, 3, 15, 20, 25, 1, 9)
(4, 6, 2, 8, 3, 15, 20, 25, 1, 9, 30)
[4, 6, 2, 8, 3, 15, 20, 25, 9, 30]
(4, 6, 2, 8, 3, 15, 20, 25, 9, 30)
-----------------------------------------------------------------------------------------------------------------
print(slice1)
#when step is negative the jump is made back
slice1 = tuplex[9:2:-4]
print(slice1)
Output No : 32
(5, 4)
(2, 4, 3, 5, 4, 6)
(6, 7, 8, 6, 1)
(2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
(3, 5, 4, 6)
('H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D')
('L', 'O', 'W', 'R')
('H', 'O', 'R')
('L', ' ')
DICTIONARIES
Dictionary is an unordered set of key and value pair.
It is a container that contains data, enclosed within curly braces.
The pair i.e., key and value is known as item. The key passed in the item must
be unique.
The key and the value is separated by a colon(:). This pair is known as item.
Items are separated from each other by a comma(,).
Different items are enclosed within a curly brace and this forms Dictionary.
Create a Dictionary
data={100:'Ravi' ,101:'Vijay' ,102:'Rahul'}
print (data)
-----------------------------------------------------------------------------------------------------------------
8. print plant[1]
9. print plant
Output:
Manoj
Hari
Ravi
{1: 'Ravi', 2: 'Manoj', 4: 'Om', 'name': 'Hari'}
-----------------------------------------------------------------------------------------------------------------
{'Salary': 20000, 'Profession': 'Trainer', 'Id': 101, 'Name': 'Ramesh'}
Whole of the dictionary can also be deleted using the del statement.
Example
data={100:'Ram', 101:'Suraj', 102:'Alok'}
del data[102]
print data
del data
print data #will show an error since dictionary is deleted.
Output:
{100: 'Ram', 101: 'Suraj'}
-----------------------------------------------------------------------------------------------------------------
Python Dictionary Methods
Methods Description Code Output
It returns all data1={100:'Ram', 101:'Suraj', dict_keys([100,
the keys 102:'Alok'} 101, 102])
keys()
element of a print(data1.keys())
dictionary.
It returns all data1={100:'Ram', 101:'Suraj', dict_values(['R
the values 102:'Alok'} am', 'Suraj',
values()
element of a print(data1.values()) 'Alok'])
dictionary.
It returns all data1={100:'Ram', 101:'Suraj', dict_items([(10
the 102:'Alok'} 0, 'Ram'), (101,
items() items(key- print(data1.items()) 'Suraj'), (102,
value pair) of 'Alok')])
a dictionary.
data1={100:'Ram', 101:'Suraj', {100: 'Ram',
It is used to 102:'Alok'} 101: 'Suraj',
add items of data2={103:'Sanjay'} 102: 'Alok',
update(dictionary2) dictionary2 data1.update(data2) 103: 'Sanjay'}
to first print (data1 ) {103: 'Sanjay'}
dictionary. print (data2) >>>
-----------------------------------------------------------------------------------------------------------------
values ?value
1?. In case
value1 is not
give, it set
the values of
keys to be
none.
data={'Id':100 , {'Id': 100,
It returns an
'Name':'Aakash' , 'Age':23} 'Name':
copy() ordered copy
data1=data.copy() 'Aakash', 'Age':
of the data.
print (data1) 23}
It returns the data={'Id':100 , 23
value of the 'Name':'Aakash' , 'Age':23} None
given key. If print (data.get('Age') )
get(key)
key is not print (data.get('Email'))
present it
returns none.
Program No : 33
Write a Python program to concatenate following dictionaries to create a new
one.
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
for d in (dic1, dic2, dic3): dic4.update(d)
print(dic4)
Output No : 33
Program No : 34
Write a Python program to sort (ascending and descending) a dictionary by
value.
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = sorted(d.items(), key=operator.itemgetter(0))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = sorted(d.items(), key=operator.itemgetter(0),reverse=True)
-----------------------------------------------------------------------------------------------------------------
print('Dictionary in descending order by value : ',sorted_d)
Output No : 34