0% found this document useful (0 votes)
58 views79 pages

Python Programming Basics Guide

This document provides a comprehensive introduction to Python, covering its basic elements, features, history, data types, and operators. It explains the structure of Python programs, the use of variables, and various control statements such as if-else and loops. Additionally, it highlights Python's versatility for different applications and its ease of learning for beginners.

Uploaded by

soniyash4095
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views79 pages

Python Programming Basics Guide

This document provides a comprehensive introduction to Python, covering its basic elements, features, history, data types, and operators. It explains the structure of Python programs, the use of variables, and various control statements such as if-else and loops. Additionally, it highlights Python's versatility for different applications and its ease of learning for beginners.

Uploaded by

soniyash4095
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to

Content
• Introduction to Python:
• The basic elements of Python,
• Objects
• Expressions and numerical Types,
• Variables and assignments,
• IDLE,
• Branching programs,
• Strings and Input,
• Iteration
• Structured Types, Mutability and Higher-order Functions:
• Tuples,
• Lists and Mutability,
• Cloning and Comprehension
• Strings,
• Tuples
• Dictionaries
Python
• Python is an object-oriented, high level language, interpreted,
dynamic and multipurpose programming language.
• Python is easy to learn yet powerful and versatile scripting
language.
• Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it.
• It is dynamically typed. (no need to declare variable with data
type).
• It is case sensitive.
• no curly braces used.
Python
• It can be used for
• Console application
• Desktop application
• Web application
• Mobile application
• Games
• Python is being used by many popular websites and applications:
• Google
• Youtube
• Instagram
• Firefox
• Dropbox
History of Python
• Python was conceptualized by Guido Van
Rossum in the late 1980s.
• Rossum published the first version of Python
code (0.9.0) in February 1991 at the CWI
(Centrum Wiskunde & Informatica) in the
Netherlands ,Amsterdam.
• Python is derived from ABC programming
language, which is a general-purpose
programming language that had been developed
at the CWI.
• Rossum chose the name "Python", since he was
a big fan of Monty Python's Flying Circus. Guido Van Rossum
• Python is now maintained by a core development
team at the institute, although Rossum still holds
a vital role in directing its progress.
Features of Python
• Easy to learn, easy to read and easy to maintain.
• Portable: It can run on various hardware platforms.
• Extendable: You can add low-level modules to the Python interpreter.
• Scalable: Python provides a good structure and support for large programs.
• Python has support for an interactive mode of testing and debugging.
• Python has a broad standard library cross-platform.
• Everything in Python is an object: variables, functions, even code.
• Python supports functional and structured programming methods as well as OOP.
• Python supports GUI applications
• Python supports automatic garbage collection.
• Python can be easily integrated with C, C++, and Java.
Basic elements of Python
• A Python Program, sometimes called a Script, is a sequence of
definitions and commands.
• These definitions are evaluated and the commands are executed by
the Python interpreter in something called the Shell.
• Typically, a new shell is created whenever execution of a program
begins.
• A Command, often called a Statement, instructs the interpreter to so
something.
• E.g., the statement print(“hello”) instructs the interpreter to call the
function print, which will output the string hello to the window
associated with the shell.
Objects, Expressions and Numerical Types
• Objects are the core things that python programs manipulate.
• Every Object has a type that defines the kinds of things that
programs can do with objects of that type.
• Objects and Operators can be combined to form Expressions.
Example : 3+2 denotes the object 5 of type int.
• A Datatype represents the type of data stored into a variable or
memory.
• The Datatypes which are already available in Python language are
called built-in datatypes.
• The Datatypes which can be created by the programmers are called
user-defined datatypes.
Keywords
• Python has a set of keywords that are reserved words that cannot
be used as variable names, function names, or any other
identifiers:
Data Types
• Built –in Datatypes:-
• None Type
• Numeric Type
• Sequences
• Sets
• Mappings
• None Type :
• It represents an object that does not contain any value.
• Maximum of only one ‘None’ object is provided.
• In Boolean expression, ‘None’ datatype represents ‘False’.
• Numeric Type :
• A numeric value is any representation of data which has a numeric value.
• Python identifies three types of numbers: int, float, complex
Data Types(1)
• Integer: Positive or negative whole numbers(without fractional part).E.g., -
57
• Float: Any real number with a floating point representation. E.g., 55.67
• Complex number: A number with a real and imaginary component
represented as x+yj. x and y are floats and j is -1(square root of -1 called
an imaginary number). E.g., -15.5j
• Boolean:-
• Data with one of two built-in values True or False. Notice that 'T' and 'F'
are capital. true and false are not valid booleans and Python will throw an
error for them.
• Sequence Type:-
• A sequence is an ordered collection of similar or different data types.
Python has the following built-in sequence data types: str, bytes,
bytearray, list,tuple,range
Data Types(2)
• String: A string value is a collection of one or more characters put in single,
double or triple quotes. E.g., str=“welcome”
• List : A list object is an ordered collection of one or more data items, not
necessarily of the same type, put in square brackets. E.g., lst=[4,5,6]
• Tuple: A Tuple object is an ordered collection of one or more data items, not
necessarily of the same type, put in parentheses. E.g., tpl=(7,8,4)
• Bytes : It represents a group of byte numbers just like an array does. A byte
number is any positive integer 0 to 255.
• E.g., arr=[7,8,9]
x=bytes(arr)
• Bytearray : similar to byte data type. The difference is that the byte array
cannot be modified but the bytearray type array can be modified.
• E.g., arr=[7,8,9]
x=bytearray(arr)
Data Types(3)
• Set :-
• It is an unordered collection of unique items. Set is defined by values
separated by comma inside braces { }. Items in a set are not ordered.
• E.g., a = {5,2,3,1,4}
• Mappings(Dictionary):-
• Dictionary is an unordered collection of key-value pairs.
• In Python, dictionaries are defined within braces {} with each item being a pair
in the form key:value.
• E.g., d = {1:'value','key':2}
Python Variables
• Variable is a name which is used to refer memory location. Variable
also known as identifier and used to hold value.
• In Python, we don't need to specify the type of variable because
Python is a type infer language and smart enough to get variable
type.
• Variable names can be a group of both letters and digits, but they
have to begin with a letter or an underscore.
• It is recommended to use lowercase letters for variable name. Rahul
and rahul both are two different variables.
• Note - Variable name should not be a keyword.
Declaring Variable and Assigning Values
• We don't need to declare explicitly variable in Python.
• When we assign any value to the variable that variable is declared
automatically.
• The equal (=) operator is used to assign value to a variable.
• Examples :
• a=10
• name=‘ravi’
• salary=12006.70
Declaring Variable and Assigning Values
• Multiple Assignment
• Python allows us to assign a value to multiple variables in a single statement
which is also known as multiple assignment.
• We can apply multiple assignments in two ways either by assigning a single value
to multiple variables or assigning multiple values to multiple variables.
1. Assigning single value to multiple variables
Eg: x=y=z=50
[Link] multiple values to multiple variables:
Eg: a,b,c=5,10,15
IDLE
• IDLE is Python’s Integrated Development and Learning
Environment.
• IDLE has the following features:
• Used for GUI Based Python.
• cross-platform: works mostly same on Windows,Unix,Mac OS X
• Python shell window with colorizing of code input, output, and
error messages
• multi-window text editor with multiple undo,smart indent, call tips,
auto completion.
• debugger with persistent breakpoints
• IDLE has two main window types, the Shell window and the Editor
window
Python Example
• A simple hello world example is given below. Write below code in a file and save
with .py extension. Python source file has .py extension.
• [Link]
• print("hello world by python!")
• Execute this example by using following command: Python3 [Link]
• Python Example using Interactive Shell
• Python interactive shell is used to test the code immediately and does not require
to write and save code in file.
• A simple python example is given below.
>>> a="Welcome To Python"
>>> print a
Welcome To Python
Python Comments
• Python supports two types of comments:
• 1) Single lined comment:
• In case user wants to specify a single line comment, then comment
must start with #.
• Eg:# This is single line comment.
2) Multi lined Comment:
• Multi lined comment can be given inside triple quotes.
• eg: ''''' This
Is
Multipline comment'''
Output
• To display output or results, python provides the print() function.
1. The print() Statement : When the print() function is called simply, it
means a blank line will be displayed.
2. The print(“string”) Statement: When string is passed to printf()
function, the string is displayed as it is.
Example : print(“hello”) / print (‘hello’)
3. The print(variables list) Statement:display the values of variables.
Example: a, b=2, 4
print(a,b) / print(a,b,sep=“,”)
4. The print(“string”, variables list) Statement: print() function is to
use strings along with variables.
Example : a=2
Input
• To accept input from keyboard, Python provides the input()
function. This function takes value from keyboard and return
it as a string.
• Examples :
1. Str=input() #no message
2. Str =input(‘Enter your name:’) #with message
3. Str=input(‘Enter a number:’) # can be converted into int
x=int(Str)
4. X=int(input(‘Enter a number:’)) #directly converted with input()
5. X=float(input(‘Enter a number:’))
Operators
• Arithmetic Operators
• Assignment Operators
• Relational (Comparison)Operators
• Logical Operators
• Bitwise Operators
• Identity Operators
• Membership Operators
Arithmetic Operators
• Arithmetic operators are used to perform mathematical
operations like addition, subtraction, multiplication, etc.
Operator Operation Example

+ Addition 5+2=7

- Subtraction 4-2=2

* Multiplication 2*3=6

/ Division 4/2=2

// Floor Division 10 // 3 = 3

% Modulo 5%2=1

** Power 4 ** 2 = 16
Assignment Operators
• Assignment operators are used to assign values to
variables. Operator Operation Example

= Assignment Operator a=7

+= Addition Assignment a += 1 # a = a + 1

-= Subtraction Assignment a -= 3 # a = a - 3

Multiplication
*= a *= 4 # a = a * 4
Assignment

/= Division Assignment a /= 3 # a = a / 3

%= Remainder Assignment a %= 10 # a = a % 10

**= Exponent Assignment a **= 10 # a = a ** 10


Comparison Operators
• Comparison operators compare two values/variables and
return a boolean result: True or False.
Operator Meaning Example

== Is Equal To 3 == 5 gives us False

!= Not Equal To 3 != 5 gives us True

> Greater Than 3 > 5 gives us False

< Less Than 3 < 5 gives us True

Greater Than or Equal


>= 3 >= 5 give us False
To

<= Less Than or Equal To 3 <= 5 gives us True


Logical Operators
• Logical operators are used to check whether an expression
is: True or False.
Operator Example Meaning

Logical AND:
and a and b
True only if both the operands are True

Logical OR:
or a or b
True if at least one of the operands is True

Logical NOT:
not not a
True if the operand is False and vice-versa.
Bitwise Operators
• Bitwise operators act on operands as if they were strings of
binary digits. They operate bit by bit, hence the name.
Operator Meaning Example

& Bitwise AND x & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x >> 2 = 2 (0000 0010)

<< Bitwise left shift x << 2 = 40 (0010 1000)


Identity Operators
• In python, is and is not are used to check if two values are
located on the same part of the memory. Two variables that
are equal does not imply that they are identical.
Operator Meaning Example

True if the operands are identical (refer to the same


is x is True
object)

True if the operands are not identical (do not refer to the
is not x is not True
same object)
Membership Operators
• In python, in and not in are the membership operators.
They are used to test whether a value or variable is found in
a sequence (string, list, tuple, set and dictionary).
Operator Meaning Example

in True if value/variable is found in the sequence 5 in x

not in True if value/variable is not found in the sequence 5 not in x


Control Statements
• Decision Statement
• Iteration Statement
Decision / Conditional /Branching Statement
• The Python if statement is a statement which is used to test specified
condition.
• We can use if statement to perform conditional operations in our
Python application.
• The if statement executes only when specified condition is true.
• We can pass any valid expression into the if parentheses.
• There are various types of if statements in Python.
• if statement
• if-else statement
• nested if statement
If Statement
• Python If Statement Syntax
if(condition):
statements
• Python If Statement Example
a=10
if a==10:
print "Welcome to javatpoint"
If Else Statement
• The If statement is used to test specified condition and if the condition
is true, if block executes, otherwise else block executes.
• The else statement executes when the if statement is false.
• Python If Else Syntax
if(condition):
True statements
else:
False statements
• Example-
year=2000
if year%4==0:
print "Year is Leap"
else: print "Year is not Leap"
Nested If Statement
• In python, we can use nested If Else to check multiple
conditions.
• Python provides elif keyword to make nested If statement.
• This statement is like executing a if statement inside a else
statement.
• Python Nested If Else Syntax
If statement:
Body
elif statement:
Body
else:
Body
Nested If Statement
• Python Nested If Else Example
a=10
if a>=20:
print "Condition is True"
else:
if a>=15:
print "Checking second value"
else:
print "All Conditions are false"
Looping/Iteration Statement [for]
• 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).
• Python For Loop Syntax
for <variable> in <sequence>:
• Python For Loop Simple Example
num=2
for a in range (1,6):
print num * a
Nested For Statement
• Loops defined within another Loop are called Nested Loops.
Nested loops are used to iterate matrix elements or to
perform complex computation.
• Python Nested For Loop Syntax
for <expression>:
for <expression>:
Body
• Python Nested For Loop Example
for i in range(1,6):
for j in range (1,i+1):
print (i)
While Statement
• In Python, while loop is used to execute number of
statements or body till the specified condition is true.
• Once the condition is false, the control will come out of the
loop.
• Python While Loop Syntax
while <expression>:
Body
• Here, loop Body will execute till the expression passed is
true. The Body may be a single statement or multiple
statement.
While Statement
• Python While Loop Example 1
a=10
while a>0:
print "Value of a is",a
a=a-2
Python Break
• Break statement is a jump statement which is used to
transfer execution control.
• It breaks the current execution and in case of inner loop,
inner loop terminates immediately.
• Python Break Example 1
for i in [1,2,3,4,5]:
if i==4:
print "Element found"
break
print (i)
Python Continue Statement
• Python Continue Statement is a jump statement which is
used to skip execution of current iteration. After skipping,
loop continue with next iteration.
• We can use continue statement with for and while statement.
• Python Continue Statement Example
a=0
while a<=5:
a=a+1
if a%2==0:
continue
print (a )
Python Pass
• In Python, 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 just makes the control to pass
by without executing any code.
• Python Pass Syntax : pass
• Python Pass Example
for i in [1,2,3,4,5]:
if i==3:
pass
print ("Pass when value is",i )
print (i)
Structured Types,
Mutability and High
order Functions
Mutability
• Every variable in python holds an instance of an object. There are two types of
objects in python i.e. Mutable and Immutable objects.
• Whenever an object is instantiated, it is assigned a unique object id. The type of
the object is defined at the runtime and it can’t be changed afterwards.
• However, it’s state can be changed if it is a mutable object.
• To summarise the difference, mutable objects can change their state or contents
is called Mutability and immutable objects can’t change their state or content.
• Immutable Objects : These are of in-built types like int, float, bool, string,
unicode, tuple. In simple words, an immutable object can’t be changed after it is
created.
• Mutable Objects : These are of type list, dict, set . Custom classes are
generally mutable.
Python Strings
• Python string is a built-in type text sequence.
• It is used to handle textual data in python.
• Python Strings are immutable sequences of Unicode points.
• We can simply create Python String by enclosing a text in
single as well as double quotes. Python treat both single and
double quotes statements same
• Both forward as well as backward indexing are provided
using Strings in Python.
• Forward indexing starts with 0,1,2,3,....
• Backward indexing starts with -1,-2,-3,-4,....
Python Strings
• Python String Example
• Here, we are creating a simple program to retrieve String in
reverse as well as normal form.
name="Rajat"
length=len(name)
i=0
for n in range(-1,(-length-1),-1):
print name[i],"\t",name[n]
i+=1
Python Strings Operators
• To perform operation on string, Python provides basically 3 types of
Operators that are given below.
• Basic Operators.
• Membership Operators.
• Relational Operators.
1. Python String Basic Operators
• There are two types of basic operators in String "+" and "*".
1.1 String Concatenation Operator (+)
• The concatenation operator (+) concatenates two Strings and
creates a new String.
• String Concatenation Example "ratan" + "jaiswal“ =ratanjaiswal
Python Strings Operators
1.2 Python String Replication Operator (*)
• The Replication operator is used to repeat a string number of times.
• Python String Replication Example 5*"Vimal"
• Output :VimalVimalVimalVimalVimal
2. Python Membership Operators
• There are two types of Membership operators
2.1 in:"in" operator returns true if a character or the entire substring is
present in the specified string, otherwise false.
2.2 not in:"not in" operator returns true if a character or entire substring
does not exist in the specified string, otherwise false.
Python Strings Operators
3. Python Relational Operators :-
• All the comparison (relational) operators i.e., (<,><=,>=,==,!=,<>) are
also applicable for strings. The Strings are compared based on the
ASCII value or Unicode(i.e., dictionary Order).
• Python Relational Operators Example
• "RAJAT"=="RAJAT"
• "afsha">='Afsha’
Python String Slice Notation
• Python String slice can be defined as a substring which is the part of
the string.
• Python String Slice Syntax
• <string_name>[startIndex:endIndex],
• <string_name>[:endIndex],
• <string_name>[startIndex:]
• Python String Slice Example
• str="Nikhil"
• str[0:3] Output :- 'Nik'
• str[:6] Output :- 'Nikhil'
Python String Functions & Methods
• Python provides various predefined or built-in string functions. They
are as follows:
No. Function Description Example Output
1 capitalize() It capitalizes the first character 'abc'.capitalize() 'Abc'
of the String.
2 count(string, It Counts number of times msg = "welcome to sssit"; 2
begin,end) substring occurs in a String substr1 = "o";
between begin and end index. print [Link](substr1, 4, 16)
3 endswith(suffix It returns a Boolean value if string1="Welcome to SSSIT"; True
,begin=0,end=n string terminates with given substr1="SSSIT";
) suffix between begin & end. print [Link](substr1);
4 find(substring It returns index value of string str="Welcome to SSSIT"; 3
,beginIndex, where substring is found substr1="come";
endIndex) between begin index & end print [Link](substr1);
index.
Python String Functions & Methods
No Function Description Example Output
5 index(substrin It throws an exception if string is not str="Welcome"; 3
g, beginIndex, found and works same as find() sub="come“;
endIndex) method.
print [Link](substr);
6 isalnum() It returns True if characters in the str="Welcome to sssit" False
string are alphanumeric i.e., alphabets print [Link]();
or numbers Otherwise it returns False.
7 isalpha() It returns True when all the characters str2="This is Python" False
are alphabets otherwise False. print [Link]();
8 isdigit() It returns True if all characters are string2="98564738" True
digit otherwise False. print [Link]();
9 islower() It returns True if the characters of a string2="welcome to " True
string are in lower case, otherwise print [Link]();
False.
Python String Functions & Methods
No Function Description Example Output
10 isupper() It returns False if characters string1="Hello Python"; False
of string are in Upper case, print [Link]();
otherwise False.
11 isspace() returns True if string is string1=" "; True
whitespace, otherwise false. print [Link]();
12 len(string) It returns length of a string. string2="WELCOME”; 7
print len(string2);
13 lower() It converts all the characters string1="Hello"; Hello
of a string to Lower case. print [Link]();
14 upper() It converts all the characters string1="Hello"; HELLO
of a string to Upper Case. print [Link]();
Python String Functions & Methods
No. Function Description Example Output
15 startswith(str It returns a Boolean value if the str1="Hello Python"; True
,begin=0,end=n) string starts with given str between print [Link]('
begin and end.
Hello');
16 swapcase() It inverts case of all characters in a str1="Hello"; hELLO
string. print [Link]();
17 lstrip() It removes all leading whitespace string1=" Hello"; Hello
of a string & can also be used to print [Link]();
remove particular character from
leading.
18 rstrip() It removes all trailing whitespace of str2="@welcome !!!" @welc
string & can also be used to print [Link]('!'); ome
remove particular character from
trailing.
Python Strings Formatting
• String formatting is also known as String interpolation.
• It is the process of inserting a custom string or variable in predefined
text.
•The format() reads the type of arguments passed to it and formats it
according to the format codes defined in the string.
• format() method takes any number of parameters. But, is divided into
two types of parameters:
•Positional parameters - list of parameters that can be accessed with
index of parameter inside curly braces {index}
•Keyword parameters - list of parameters of type key=value, that can
be accessed with key of parameter inside curly braces {key}
Python Strings Formatting
•#default arguments
print("Hello {}, your balance is {}.".format("Adam", 230.2346))

# positional arguments
print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))

# keyword arguments
print("Hello {name}, your balance is {blc}.".format(name="Adam",
blc=230.2346))

•# mixed arguments
print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))
Python Strings Formatting Number Formatting Types
• Type
You can format numbers using the format specifier given below:
Meaning
d Decimal integer
c Corresponding Unicode character
b Binary format
o Octal format
x Hexadecimal format (lower case)
X Hexadecimal format (upper case)
n Same as 'd'. Except it uses current locale setting for number separator
e Exponential notation. (lowercase e)
E Exponential notation (uppercase E)
f Displays fixed point number (Default: 6)
F Same as 'f'. Except displays 'inf' as 'INF' and 'nan' as 'NAN'
g General format. Rounds number to p significant digits. (Default precision: 6)
G Same as 'g'. Except switches to 'E' if the number is large.
% Percentage. Multiples by 100 and puts % at the end.
Python List
• Python list is a data structure which is used to store various
types of data.
• In Python, lists are mutable i.e., Python will not create a new list if
we modify an element of the list.
• It works as a container that holds other objects in a given order. We
can perform various operations like insertion and deletion on list.
• A list can be composed by storing a sequence of different type of
values separated by commas.
• Python list is enclosed between square([]) brackets and elements
are stored in the index basis with starting index 0.
Python List
• Syntax: <list_name>=[value1,value2,value3,...,valuen];
• Example: data=['abhinav',10,56.4,'a'];
• Access List: print data[0:2]
• Elements in List: print data[0:2]
Python List Operation
1. Adding Python List :
• In Python, lists can be added by using the concatenation
operator(+) to join two lists.
• Example: list1=[10,20]
list2=[30,40]
list3=list1+list2
print list3
• Output: [10, 20, 30, 40 ]
2. Replicating Python List : Replicating means repeating, It can be
performed by using '*' operator by a specific number of time.
• Example : list1=[10,20]
print list1*1
Python List Operation
3. Python List Slicing : A subpart of a list can be retrieved on the
basis of index. This subpart is known as list slice. This feature
allows us to get sub-list of specified start and end index.
• Example: list1=[1,2,4,5,7]
• print list1[0:2]
• Output: [1,2]
4. Python Updating lists : To update or change the value of particular
index of a list, assign the value to that particular index of the List.
• Example: data1=[5,10,15,20,25]
data1[2]="Multiple of 5"
print data1
• Output: [5, 10, 'Multiple of 5', 20, 25]
Python List Operation
5. Appending Python List: Python provides, append() method which
is used to append i.e., add an element at the end of the existing
elements.
• Example: list1=[10,"rahul",'z']
[Link](10.45)

4. Deleting Elements: In Python, del statement can be used to delete


an element from the list. It can also be used to delete all items from
startIndex to endIndex.
• Example: list1=[10,'rahul',50.8,'a',20,30]
del list1[0]
Python List Function
N Function Description Example Output
o
1 min(list) It returns the minimum l=[101,981,'abcd','xyz‘] 101
value from the list given. print min(l)
2 max(list) It returns the largest value l=[‘ram','shekhar',100] Shekhar
from the given list. print max(l)
3 len(list) It returns number of l=[101,981,'abcd','xyz‘] 4
elements in a list. print len(l)
4 list(sequence) It takes sequence types seq=(145,"abcd",'a') [145,”abcd”,’a’]
and converts them to lists. data=list(seq)
print data
Python List Methods
No Function Description Example Output

1 index(object) It returns the index value of data = [786,'abc','a',123.5] 3


the object. Print [Link](123.5)

2 count(object) It returns the number of data = [786,'a‘,786,'rahul','b’] 2


times an object is repeated in print [Link](786)
list.

3 pop()/pop(index) It returns the last object or data = [786,'abc','a',123.5,786] [786,


the specified indexed object. [Link]() ‘abc’,’a’,123.5, 786]
It removes the popped print data
object.

4 insert(index,obje It inserts an object at the data=['abc',123,10.5,'a'] [‘abc’,123, ‘hello’,


ct) given index. [Link](2,'hello') 10.5, ‘a’]
print data
Python List Methods
No Function Description Example Output

5 extend(sequen It adds the sequence to data1=['abc',123 ] [‘abc’ 123, ‘ram’,


ce) existing list. data2=['ram',541] 541 ]
[Link](data2)
6 remove(object) It removes the object from data1=['abc',123,10.5,'a','xy [‘abc’,123,10.5,’
the given List. z'] a’]
print data1
[Link]('xyz')
7 reverse() It reverses the position of list1=[10,20,30,40,50] [50,40,30,20,10]
all the elements of a list. [Link]()
print list1
8 sort() It is used to sort the list1=[10,50,13,'rahul','aaka [10,13,50,
elements of the List. sh'] ‘aakash’,’rahul’]
[Link]()
print list1
Python Tuples
• A tuple is a sequence of immutable objects, therefore tuple
cannot be changed.
• It can be used to collect different types of object.
• The objects are enclosed within parenthesis and separated by
comma.
• Tuple is similar to list.
• Only the difference is that list is enclosed between square bracket,
tuple between parenthesis and List has mutable objects whereas
Tuple has immutable objects.
Python Tuples
• Python Tuple Example
>>> data=(10,20,'ram',56.8)
>>> data2="a",10,20.9
>>> data
Output:-(10, 20, 'ram', 56.8)
>>> data2
Output:-('a', 10, 20.9)
• NOTE: If Parenthesis is not given with a sequence, it is by default
treated as Tuple
• Python Empty Tuple : There can be an empty Tuple also which
contains no object.
• Example : tuple1=()
Python Tuples
• Accessing Tuple: Accessing of tuple is prity easy, we can access
tuple in the same way as List. See, the following example.
• Example : data1=(1,2,3,4)
print data1[0:]
print data1[:2]
print data2[-3:-1]
• Why should wee use Tuple? (Advantages of Tuple)
1. Processing of Tuples are faster than Lists.
2. It makes the data safe as Tuples are immutable and hence cannot be changed.
3. Tuples are used for String formatting.
Python Tuples Operations
1. Adding Tuples: Tuple can be added by using the concatenation
operator(+) to join two tuples.
• Example : data1=(1,2,3,4)
data2=('x','y','z')
data3=data1+data2
• Output: (1, 2, 3, 4, 'x', 'y', 'z')
2. Replicating Tuples: It can be performed by using '*' operator by a
specific number of time.
• Example : tuple1=(10,20,30);
print tuple1*2
• Output: (10,20,30,10,20,30)
Python Tuples Operations
3. Tuples Slicing: A subpart of a tuple can be retrieved on the basis of
index. This subpart is known as tuple slice.
• Example :data1=(1,2,4,5,7)
print data1[0:2]
• Output: (1, 2)
• 4. Deleting Tuples: Deleting individual element from a tuple is not
supported. However the whole of the tuple can be deleted using the
del statement.
• Example :data=(10,20,'rahul',40.6,'z')
del data
Python Tuple Function
N Function Description Example Output
o
1 min(tuple) It returns the minimum l=(101,981,'abcd','xyz‘) 101
value from the tuple. print min(l)
2 max(tuple) It returns the largest value l=(‘ram','shekhar',100) Shekhar
from the given tuple print max(l)
3 len(tuple) It returns number of l=(101,981,'abcd','xyz‘) 4
elements in a list. print len(l)
4 tuple(sequence It takes sequence types seq=(145,"abcd",'a') (145,”abcd”,’a’)
) and converts them to data=tuple(seq)
tuples print data
Python Dictionary
• 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(:). Items are
separated from each other by a comma(,).
• Note: Dictionary is mutable i.e., value can be updated.
• Value is accessed by key. Value can be updated while key cannot be
changed.
• Dictionary is known as Associative array since the Key works as
Index and they are decided by the user.
Python Dictionary Example
• Example 1: data={100:'Ravi' ,101:'Vijay' ,102:'Rahul'}
print data
• Output: {100: 'Ravi', 101: 'Vijay', 102: 'Rahul'}

• Example 2: plant={}
plant[1]='Ravi'
plant[2]='Manoj'
plant['name']='Hari'
plant[4]='Om'
print plant
Accessing Python Dictionary
• A Dictionary values can be accessed by their keys only. It means, to
access dictionary elements we need to pass key, associated to the
value.
• Python Accessing Dictionary Element Syntax
<dictionary_name>[key]
</dictionary_name>
• Accessing Elements Example
data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
print data1['Id'] -> 100
print data1['Name'] ->Suresh
Updating Python Dictionary Elements
• The item i.e., key-value pair can be updated. Updating means new
item can be added. The values can be modified.
• Example
data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
data1['Profession']='Manager'
data1['Salary']=15000
print data1
• Output : {'Salary': 15000, 'Profession': 'Manager','Id': 100, 'Name':
'Suresh'}
Deleting Python Dictionary Elements
• del statement is used for performing deletion operation.
• An item can be deleted from a dictionary using the key only.
• Delete Syntax
del <dictionary_name>[key]
</dictionary_name>
• Whole of the dictionary can also be deleted using the del statement.
• Example
data={100:'Ram', 101:'Suraj', 102:'Alok'}
del data[102] #single item
del data #whole dictionary
Python Dictionary Functions &
Methods
No Functions Description Example Output
1 len(dictionary) It returns number of items in a data={100:'Ram', 101:'Suraj‘} 3
dictionary. print len(data)

No Methods Description Example Output


1 keys() It returns all the keys element of a d1={100:'Ram', 101:'Suraj‘} [100, 101]
dictionary. print [Link]()
2 values() It returns all the values element of a d1={100:'Ram', 101:'Suraj‘} ['Ram',
dictionary. print [Link]() 'Suraj‘ ]
3 items() It returns all the items(key-value pair) of d1={100:'Ram', 101:'Suraj‘} [(100,
a dictionary. print [Link]() 'Ram'), (101,
'Suraj') ]
Python Dictionary Methods
No Methods Description Example Output
4 update(dicti It is used to add items of dictionary2 to d1={100:'Ram', 101:'Suraj‘} {100: 'Ram',
onary2) first dictionary. d2={102:'Sanjay'} 101:'Suraj‘,
[Link](d2) 102:Sanjay'}
print d1
5 clear() It is used to remove all items of a d1={100:'Ram',101:'Suraj’ } {}
dictionary. It returns an empty dictionary. [Link]()
print d1
6 fromkeys( It is used to create a new dictionary from seq=('Id' , 'Email') {'Email':
sequence,v sequence where sequence elements forms d={} None, 'Id':
alue1)/ key & all keys share same values. In case d1={} None}
fromkeys( value1 is not give, it set the values of d=[Link](seq)
sequence) keys to be none. print data
7 copy() It returns an ordered copy of the data. d={'Id':100,'Age':23} {'Age': 23,
d1=[Link]() 'Id': 100}
Print d1
Python Dictionary Methods
No Methods Description Example Output
8 get(key) It returns the value of the given key. If key d={'Id':100 , 'Age':23} 23
is not present it returns none print [Link]('Age')
9 pop() remove specified key and return the d={'Id':100 , 'Age':23} d={'Id'
corresponding [Link] key is not found, d is [Link](‘Age’) :100}
returned if given, otherwise KeyError is
raised
print(d)
10 popitem() Removes last item from dictionary d={'Id':100 , 'Age':23} d={'Id'
[Link]() :100}
print(d)

You might also like