Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views29 pages

Python

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)
4 views29 pages

Python

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
You are on page 1/ 29

UNIT-1

Python: is a dynamic, high-level, free open source, and interpreted programming


language. It supports object-oriented programming as well as procedural-oriented
programming. In Python, we don’t need to declare the type of variable because it
is a dynamically typed language.
Features of Python
1- Easy to Code Python is a very developer-friendly language which means
that anyone and everyone can learn to code it in a couple of hours or days
2- Open Source and Free: Python is an open-source programming language
which means that anyone can create and contribute to its development
3- Support for GUI: GUI or Graphical User Interface is one of the key aspects
of any programming language because it has the ability to add flair to code
and make the results more visual.
4- Object-Oriented Approach: One of the key aspects of Python is its object-
oriented approach. This basically means that Python recognizes the concept
of class and object encapsulation thus allowing programs to be efficient in
the long run.
5- High-Level Language: Python has been designed to be a high-level
programming language, which means that when you code in Python you
don’t need to be aware of the coding structure, architecture as well as
memory management.
6- Python is an integrated language by nature: This means that the python
interpreter executes codes one line at a time.
7- Highly Portable: Suppose you are running Python on Windows and you
need to shift the same to either a Mac or a Linux system, then you can
easily achieve the same in Python without having to worry about changing
the code.

An "environment" in Python is the context in which a Python program runs. An


environment consists of an interpreter and any number of installed packages.

1
An Interpreter: An Interpreter is a program that converts the code a developer
writes into an intermediate language, called the byte code. It converts the code
line by line, one at a time. It translates till the end and stops at that line where an
error occurs, if any, making the debugging process easy.

The interactive mode of Python is also called REPL.


REPL stands for ‘Read-Eval-Print-Loop’. It is a simple, interactive command-line
shell that provides us with the result when provided with a single line Python
command.
1. Read: The read function accepts an input from the user and stores it into the
memory.
2. Eval: The eval function evaluates this ‘input’ read from the memory.
3. Print: The print function prints the outcome from the eval function.
4. Loop: The loop function creates a loop and terminates itself when the program
ends.
This was a brief explanation of the interactive mode: REPL.

Data types: The data stored in memory can be of many types. For example, a
student roll number is stored as a numeric value and his or her address is stored
as alphanumeric characters. Python has various standard data types that are used
to define the operations possible on them and the storage method for each of
them.
Int: Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.
Float: Float, or "floating point number" is a number, positive or negative,
containing one or more
decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
Boolean: Objects of Boolean type may have one of two values, True or False.
String: 1. Strings in Python are identified as a contiguous set of characters
represented in the
quotation marks. Python allows for either pairs of single or double quotes.
• 'hello' is the same as "hello".
• Strings can be output to screen using the print function. For example:
print("hello"). If you want to include either type of quote character within the

2
string, the simplest way is to delimit the string with the other type. If a string is to
contain a single quote, delimit it with double quotes and vice versa:
>>> print ("mac is a minority (') college")

Special Character: Specifying a backslash (\) in front of the quote character in a


string “escape” it and causes Python to suppress its usual special meaning. It is
then interpreted simply as a literal single
quote character:
>>> print ("mac is a minority (\') college")
mac is a minority (') college

List:
• It is a general purpose most widely used in data structures
• List is a collection which is ordered and changeable and allows duplicate
members.
(Grow and shrink as needed, sequence type, sortable).
• To use a list, you must declare it first. Do this using square brackets and
separate
values with commas.
• We can construct / create list in many ways.
Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]

Variables: Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning
different data types to variables, you can store integers, decimals or characters in
these variables. Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-
z, 0-9, and )

3
• Variable names are case-sensitive (age, Age and AGE are three different
variables)
Assigning Values to Variables:
Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The
equal sign (=) is used to assign values to variables. The operand to the left of the =
operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable.

Expressions: An expression is a combination of values, variables, and operators.


An expression is evaluated using assignment operator. Examples: Y=x + 17

Identifiers: Any name that is used to define a class, function, variable module, or
object is an identifier.
Literals: These are language-independent terms in Python and should exist
independently in any programming language. In Python, there are the string
literals, byte literals, integer literals, floating point literals, and imaginary literals.
Operators: In Python you can implement the following operations using the
corresponding tokens.

Statements: A statement is an instruction that the Python interpreter can


execute. We have normally two basic statements, the assignment statement and
the print statement. Some other kinds of statements that are if statements, while
statements, and for statements generally called as control flows. Examples:
An assignment statement creates new variables and gives them values:
>>> x=10

Precedence of Operators: Operator precedence affects how an expression is


evaluated. For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because
operator * has higher precedence than +, so it first multiplies 3*2 and then adds
into 7. Example 1: >>> 3+4*2

4
Modules: Python module can be defined as a python program file which contains
a python code including python functions, class, or variables. In other words, we
can say that our python code file saved with the extension (.py) is treated as the
module. We may have a runnable code inside the python module. A module in
Python provides us the flexibility to organize the code in a logical way. To use the
functionality of one module into another, we must have to import the specific
module. Syntax: import <module-name>

Functions and its use: Function is a group of related statements that perform 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. It avoids repetition and makes code reusable. Basically, we can
divide functions into the following two types:
Built-in functions - Functions that are built into Python.
Ex: abs(),all().ascii(),bool().........so on....
User-defined functions - Functions defined by the users themselves.
def add numbers(x,y):
sum = x + y
return sum
print ("The sum is", add numbers (5, 20))

Flow of Execution:
1. The order in which statements are executed is called the flow of execution
2. Execution always begins at the first statement of the program.
3. Statements are executed one at a time, in order, from top to bottom.
4. Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the function
is called.
5. Function calls are like a bypass in the flow of execution. Instead of going to the
next statement, the flow jumps to the first line of the called function, executes all
the statements there, and then comes back to pick up where it left off.

5
Function definition consists of following components:
1. Keyword def indicates the start of function header.
2. A function name to uniquely identify it. Function naming follows the same rules
of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are
optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body.
Statements must have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

#Keyword Arguments When we call a function with some values, these values get
assigned to the arguments according to their position. Python allows functions to
be called using keyword arguments. When we call functions in this way, the order
(position) of the arguments can be changed.

#Default Arguments Function arguments can have default values in Python.


We can provide a default value to an argument by using the assignment operator
(=)
def hello (wish,name='you'):
return '{},{}'.format(wish ,name)
print(hello("good morning"))

Variable-length arguments
Sometimes you may need more arguments to process function then you
mentioned in the definition. If we don’t know in advance about the arguments
needed in function, we can use variable-length arguments also called arbitrary
arguments. For this an asterisk (*) is placed before a parameter in function
definition which can hold non-keyworded variable-length arguments and a double
asterisk (**) is placed before a parameter in function which can hold keyworded
variable-length arguments.

6
UNIT-2
CONTROL FLOW, LOOPS
Conditionals: Boolean values and operators, conditional (if), alternative (if-else),
chained conditional (if-elif-else); Iteration: while, for, break, continue.

Control Flow, Loops: Boolean Values and Operators:


A Boolean expression is an expression that is either true or false. The following
Examples use the operator ==, which compares two operands and produces True
if they are equal and False otherwise.

Conditional (if): The if statement contains a logical expression using which data is
compared and a decision is made based on the result of the comparison.
Syntax: if expression: statement(s) If the Boolean expression evaluates to TRUE,
then the block of statement(s) inside the if statement is executed. If Boolean
expression evaluates to FALSE, then the first set of code after the end of the if
statement(s) is executed.

Alternative if (If-Else): An else statement can be combined with an if statement.


An else statement contains the block of code (false block) that executes if the
conditional expression in the if statement resolves to 0 or a FALSE value. The else
statement is an optional statement and there could be at most only one else
Statement following if.

Chained Conditional: (If-elif-else): The elif statement allows us to check multiple


expressions for TRUE and execute a block of code as soon as one of the conditions
evaluates to TRUE. Similar to the else, the elif statement is optional. However,
unlike else, for which there can be at most one statement, there can be an
arbitrary number of elif statements following an if.

7
Iteration: A loop statement allows us to execute a statement or group of
statements multiple times as long as the condition is true. Repeated execution of
a set of statements with the help of loops is called iteration. Loops statements are
used when we need to run same code again and again, each time with a different
value.

Statements: In Python Iteration (Loops) statements are of three types:


1. While Loop
2. For Loop
3. Nested For Loops

While loop:
• Loops are either infinite or conditional. Python while loop keeps reiterating a
block of code defined inside it until the desired condition is met.
• The while loop contains a boolean expression and the code inside the loop is
repeatedly executed as long as the boolean expression is true.
• The statements that are executed inside while can be a single line of code or a
block of multiple statements.
Syntax:
while(expression):
Statement(s)

For loop: Python for loop is used for repeated execution of a group of statements
for the desired number of times. It iterates over the items of lists, tuples, strings,
the dictionaries and other iterable objects.

8
Nested For loop: When one Loop defined within another Loop is called Nested
Loops.
Syntax:
for val in sequence:
for val in sequence:

In Python, break and continue statements can alter the flow of a normal loop.
Sometimes we wish to terminate the current iteration or even the whole loop
without checking test expression. The break and continue statements are used in
these cases.
Break: The break statement terminates the loop containing it and control of the
program flows to the statement immediately after the body of the loop. If break
statement is inside a nested loop (loop inside another loop), break will terminate
the innermost loop.

Continue: The continue statement is used to skip the rest of the code inside a
loop for the current iteration only. Loop does not terminate but continues on with
the next iteration.

Pass: In Python programming, pass is a null statement. The difference between


a comment and pass statement in Python is that, while the interpreter ignores a
comment entirely, pass is not ignored. pass is just a placeholder for functionality
to be added later.
Example:
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass

9
UNIT – III
FUNCTIONS, ARRAYS
Fruitful functions: return values, parameters, local and global scope, function
composition, recursion; Strings: string slices, immutability, string functions and
methods, string module; Python arrays, Access the Elements of an Array, array
methods.
Functions, Arrays:
Fruitful functions:
We write functions that return values, which we will call fruitful functions. We
have seen the return statement before, but in a fruitful function the return
statement includes a return value. This statement means: "Return immediately
from this function and use the following expression as a return value."

Return values:
The Keyword return is used to return back the value to the called function.
# returns the area of a circle with the given radius:
def area(radius):
temp = 3.14 * radius**2
return temp
print(area(4))

Sometimes it is useful to have multiple return statements, one in each branch of a


conditional:
def absolute_value(x):
if x < 0:
return -x
else:
return x
Since these return statements are in an alternative conditional, only one will be
executed. As soon as a return statement executes, the function terminates
without executing any subsequent statements. Code that appears after a return
statement, or any other place the flow of execution can never reach, is called

10
dead code. In a fruitful function, it is a good idea to ensure that every possible
path through the program hits a return statement. For example:
def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x
This function is incorrect because if x happens to be 0, both conditions is true, and
the function ends without hitting a return statement. If the flow of execution gets
to the end of a function, the return value is None, which is not the absolute value
of 0.
>>> print absolute_value(0)
None
By the way, Python provides a built-in function called abs that computes absolute
values.

# Write a Python function that takes two lists and returns True if they have at
least one
common member.
def common_data(list1, list2):
for x in list1:
for y in list2:
if x == y:
result = True
return result

print(common_data([1,2,3,4,5], [1,2,3,4,5]))
print(common_data([1,2,3,4,5], [1,7,8,9,510]))
print(common_data([1,2,3,4,5], [6,7,8,9,10]))
Output:

True
True
None

11
Parameters:
Parameters are passed during the definition of function while Arguments are
passed during the function call.
Example:
#here a and b are parameters
def add(a,b): #//function definition
return a+b
#12 and 13 are arguments
#function call
result=add(12,13)
print(result)
Output:
25

Local and Global scope:


Local Scope: A variable which is defined inside a function is local to that function.
It is accessible from the point at which it is defined until the end of the function,
and exists for as long as the function is executing
Global Scope:
A variable which is defined in the main body of a file is called a global variable. It
will be visible throughout the file, and also inside any file which imports that file.
• The variable defined inside a function can also be made global by using the
global
statement.
def function_name(args):
.............
global x #declaring global variable inside a function
..............

# create a global variable


x = "global"
def f():
print("x inside :", x)
12
f()
print("x outside:", x)
Output:
x inside : global
x outside: global

# create a local variable


def f1():
y = "local"
print(y)
f1()
Output:
Local

• If we try to access the local variable outside the scope for example,
def f2():
y = "local"
f2()
print(y)
Then when we try to run it shows an error,
Traceback (most recent call last):
print(y)
NameError: name 'y' is not defined
The output shows an error, because we are trying to access a local variable y in a
global scope whereas the local variable only works inside f2() or local scope.

# use local and global variables in same code


x = "global"
def f3():
global x
y = "local"
x=x*2
print(x)
print(y)
f3()
13
Output:
Global local

• In the above code, we declare x as a global and y as a local variable in the f3().
Then, we use multiplication operator * to modify the global variable x and we
print both x and y.
• After calling the f3(), the value of x becomes global global because we used the
x *2 to print two times global. After that, we print the value of local variable y i.e
local.

# use Global variable and Local variable with same name


x=5
def f4():
x = 10
print("local x:", x)
f4()
print("global x:", x)
Output:
local x: 10
global x: 5

Function Composition:
Having two (or more) functions where the output of one function is the input for
another. So for example if you have two functions FunctionA and FunctionB you
compose them by doing the following.
FunctionB(FunctionA(x))
Here x is the input for FunctionA and the result of that is the input for FunctionB.
Example 1:
#create a function compose2
>>> def compose2(f, g):
return lambda x:f(g(x))
>>> def d(x):
return x*2
>>> def e(x):
return x+1
14
>>> a=compose2(d,e) # FunctionC = compose(FunctionB,FunctionA)
>>> a(5) # FunctionC(x)
12

In the above program we tried to compose n functions with the main function
created.
Example 2:
>>> colors=('red','green','blue')
>>> fruits=['orange','banana','cherry']
>>> zip(colors,fruits)
<zip object at 0x03DAC6C8>
>>> list(zip(colors,fruits))
[('red', 'orange'), ('green', 'banana'), ('blue', 'cherry')]

Recursion: Recursion is the process of defining something in terms of itself.


Python Recursive Function We know that in Python, a function can call other
functions. It is even possible for the function to call itself. These types of
constructs are termed as recursive functions. Factorial of a number is the product
of all the integers from 1 to that number. For example,
the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Following is an example of recursive function to find the factorial of an integer.
# Write a program to factorial using recursion
def fact(x):
if x==0:
result = 1
else :
result = x * fact(x-1)
return result
print("zero factorial",fact(0))
print("five factorial",fact(5))
Output:
zero factorial 1
five factorial 120

15
Strings: A string is a group/ a sequence of characters. Since Python has no
provision for arrays, we simply use strings. This is how we declare a string. We can
use a pair of single or double quotes. Every string object is of the type ‘str’.
>>> type("name")
<class 'str'>
>>> name=str()
>>> name
''
>>> a=str('mrcet')
>>> a
'mrcet'
>>> a=str(mrcet)
>>> a[2]
'c'
>>> fruit = 'banana'
>>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to
letter. The expression in brackets is called an index. The index indicates which
character in the sequence we want
String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a
character: Subsets of strings can be taken using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the string and working their way from -1
at the end. Slice out substrings, sub lists, sub Tuples using index.
Syntax:[Start: stop: steps]
• Slicing will start from index and will go up to stop in step of steps.
• Default value of start is 0,
• Stop is last index of list
• And for step default is 1

For example 1−
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
16
print str[2:] # Prints string starting from 3rd character print
str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Immutability: It is tempting to use the [] operator on the left side of an


assignment, with the intention of changing a character in a string.
For example:
>>> greeting='mrcet college!'
>>> greeting[0]='n'
TypeError: 'str' object does not support item assignment
The reason for the error is that strings are immutable, which means we can’t
change an existing string. The best we can do is creating a new string that is a
variation on the original:
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> new_greeting
'Hello, world!'
Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator

17
Note:
All the string methods will be returning either true or false as the result
1. isalnum():
Isalnum() method returns true if string has at least 1 character and all characters
are alphanumeric and false otherwise.
Syntax: String.isalnum()
2. isalpha(): isalpha() method returns true if string has at least 1 character and all
characters are alphabetic and false otherwise. Syntax: String.isalpha()
3. isdigit(): isdigit() returns true if string contains only digits and false otherwise.
Syntax: String.isdigit()
4. islower(): Islower() returns true if string has characters that are in lowercase
and false otherwise. Syntax: String.islower()
5. isnumeric(): isnumeric() method returns true if a string contains only numeric
characters and false otherwise. Syntax: String.isnumeric()
6. isspace(): isspace() returns true if string contains only whitespace characters
and false otherwise. Syntax: String.isspace()

18
7. istitle() istitle() method returns true if string is properly “titlecased”(starting
letter of each word is capital) and false otherwise Syntax: String.istitle()
8. isupper() isupper() returns true if string has characters that are in uppercase
and false otherwise. Syntax: String.isupper()
9. replace() replace() method replaces all occurrences of old in string with new or
at most max occurrences if max given. Syntax: String.replace()
10.split() split() method splits the string according to delimiter str (space if not
provided) Syntax: String.split()
11.count(): count() method counts the occurrence of a string in another string
Syntax: String.count()
12.find(): Find() method is used for finding the index of the first occurrence of a
string in another string Syntax: String.find(„string‟)
13.swapcase() converts lowercase letters in a string to uppercase and viceversa
Syntax: String.find(„string‟)
14.startswith(): Determines if string or a substring of string (if starting index beg
and ending index end are given) starts with substring str; returns true if so and
false otherwise. Syntax: String.startswith(„string‟)
15.endswith() Determines if string or a substring of string (if starting index beg
and ending index end are given) ends with substring str; returns true if so and
false otherwise. Syntax: String.endswith(„string‟)

String module:
This module contains a number of functions to process standard Python strings. In
recent versions, most functions are available as string methods as well.
It’s a built-in module and we have to import it before using any of its constants
and classes Syntax: import string
Note:
help(string) --- gives the information about all the variables ,functions, attributes
and classes to be used in string module.

Python String Module Classes


Python string module contains two classes – Formatter and Template.
Formatter It behaves exactly same as str.format() function. This class becomes
useful if you want to subclass it and define your own format string syntax.

19
Syntax: from string import Formatter Template This class is used to create a string
template for simpler string substitutions
Syntax: from string import Template
Python arrays: Array is a container which can hold a fix number of items and
these items should be of the same type. Most of the data structures make use of
arrays to implement their algorithms. Following are the important terms to
understand the concept of Array.
• Element− Each item stored in an array is called an element.
• Index − Each location of an element in an array has a numerical index, which is
used to identify the element.
Array Representation: Arrays can be declared in various ways in different
languages. Below is an illustration.
Elements Int array [10] = {10, 20, 30, 40, 50, 60, 70, 80, 85, 90}
Type Name Size Index 0 As per the above illustration, following are the important
points to be considered.
• Index starts with 0.
• Array length is 10 which means it can store 10 elements.
• Each element can be accessed via its index. For example, we can fetch an
element at
index 6 as 70
Basic Operations
Following are the basic operations supported by an array.
• Traverse − print all the array elements one by one.
• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given index or by the value.
• Update − Updates an element at the given index.
Array is created in Python by importing array module to the python program.
Then the array is declared as shown below.
from array import *
arrayName=array(typecode, [initializers])
Typecode are the codes that are used to define the type of value the array will
hold. Some common typecodes used are:

20
Creating an array:
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)
Output:
>>>
10
20
30
40
50

Access the elements of an Array: Accessing Array Element


We can access each element of an array using the index of the element.
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2])
Output:
10
30

21
Array methods:
Python has a set of built-in methods that you can use on lists/arrays.

22
UNIT – IV
LISTS, TUPLES, DICTIONARIES
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning
lists, list parameters, list comprehension; Tuples: tuple assignment, tuple as
return value, tuple comprehension; Dictionaries: operations and methods,
comprehension;
Lists, Tuples, Dictionaries:
List:
• It is a general purpose most widely used in data structures
• List is a collection which is ordered and changeable and allows duplicate
members. (Grow and shrink as needed, sequence type, sortable).
• To use a list, you must declare it first. Do this using square brackets and
separate values with commas.
• We can construct / create list in many ways.

List operations:
These operations include indexing, slicing, adding, multiplying, and checking for
Membership.
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.
List methods: The list data type has some more methods. Here are all of the
methods of list objects:
• Del()
• Append()
• Extend()
• Insert()
• Pop()
• Remove()
• Reverse()
• Sort()

23
Pop: The pop() method removes the specified index, (or the last item if index is
not specified) or simply pops the last item of list and returns the item.
Remove: The remove() method removes the specified item from a given list.
Reverse: Reverse the order of a given list.
Sort: Sorts the elements in ascending order

Mutability: A mutable object can be changed after it is created, and an


immutable object can't.
Append: Append an item to a list.
Delete: Delete a list or an item from a list
Pop: The pop() method removes the specified index, (or the last item if index is
not specified) or simply pops the last item of list and returns the item.
Remove: The remove() method removes the specified item from a given list.
Reverse: Reverse the order of a given list.
Sort: Sorts the elements in ascending order

Aliasing:
1. An alias is a second name for a piece of data, often easier (and more useful)
than making a copy.
2. If the data is immutable, aliases don’t matter because the data can’t change.
3. But if data can change, aliases can result in lot of hard – to – find bugs.
4. Aliasing happens whenever one variable’s value is assigned to another variable.

Cloning Lists: If we want to modify a list and also keep a copy of the original, we
need to be able to make a copy of the list itself, not just the reference. This
process is sometimes called cloning, to avoid the ambiguity of the word copy.
The easiest way to clone a list is to use the slice operator. Taking any slice of a
creates a new list. In this case the slice happens to consist of the whole list.

List parameters:
Passing a list as an argument actually passes a reference to the list, not a copy of
the list. Since lists are mutable, changes made to the elements referenced by the
parameter change the same list that the argument is referencing.

24
List comprehension:
List:
List comprehensions provide a concise way to create lists. Common applications
are to make new lists where each element is the result of some operations
applied to each member of another sequence or iterable, or to create a
subsequence of those elements that satisfy a certain condition.

Tuples: A tuple is a collection which is ordered and unchangeable. In Python


tuples are written with round brackets.
• Supports all operations for sequences.
• Immutable, but member objects may be mutable.
• If the contents of a list shouldn’t change, use a tuple to prevent items from
accidently being added, changed, or deleted.
• Tuples are more efficient than list due to python’s implementation.

Access tuple items: Access tuple items by referring to the index number, inside
square brackets.
Change tuple items: Once a tuple is created, you cannot change its values. Tuples
are unchangeable.
Tuple Assignment Python has tuple assignment feature which enables you to
assign more than one variable at a time. In here, we have assigned tuple 1 with
the college information like college name, year, etc. and another tuple 2 with the
values in it like number (1, 2, 3... 7).
Tuple as return values: A Tuple is a comma separated sequence of items. It is
created with or without (). Tuples are immutable.
Tuple comprehension: Tuple Comprehensions are special: The result of a tuple
comprehension is special. You might expect it to produce a tuple, but what it does
is produce a special "generator" object that we can iterate over.
Set: Similarly, to list comprehensions, set comprehensions are also supported:
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

25
Dictionaries: A dictionary is a collection which is unordered, changeable and
indexed. In Python dictionaries are written with curly brackets, and they have
keys and values.
• Key-value pairs
• Unordered
We can construct or create dictionary like:
X={1:’A’,2:’B’,3:’c’}
X=dict([(‘a’,3) (‘b’,4)]
X=dict(‘A’=1,’B’ =2)

Operations and methods:


Methods that are available with dictionary are tabulated below. Some of them
have already been used in the above examples.

26
Below are some dictionary operations:
To access specific value of a dictionary, we must pass its key,
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> x=dict1["brand"]
>>> x 'mrcet'
To access keys and values and items of dictionary:
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> dict1.keys() dict_keys(['brand', 'model', 'year'])
>>> dict1.values() dict_values(['mrcet', 'college', 2004])
>>> dict1.items() dict_items([('brand', 'mrcet'), ('model', 'college'), ('year', 2004)]
>>> for items in dict1.values(): print(items) mrcet college 2004
>>> for items in dict1.keys(): print(items) brand model year
>>> for i in dict1.items(): print(i) ('brand', 'mrcet') ('model', 'college') ('year', 2004)

Some more operations like:


• Add/change • Remove • Length • Delete
Add/change values: You can change the value of a specific item by referring to its
key name
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> dict1["year"]=2005
>>> dict1 {'brand': 'mrcet', 'model': 'college', 'year': 2005} Remove(): It removes
or pop the specific item of dictionary.
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> print(dict1.pop("model")) college
>>> dict1 {'brand': 'mrcet', 'year': 2005} Delete: Deletes a particular item.
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> del x[5]
>>> x Length: we use len() method to get the length of dictionary.
>>>{1: 1, 2: 4, 3: 9, 4: 16} {1: 1, 2: 4, 3: 9, 4: 16}
>>> y=len(x)
>>> y 4 Iterating over (key, value) pairs:
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> for key in x: print(key, x[key])
11
24
27
39
101
4 16
5 25
>>> for k,v in x.items():
print(k,v)
11
24
39
4 16
5 25

28
List of Dictionaries:
>>> customers = [{"uid":1,"name":"John"}, {"uid":2,"name":"Smith"},
{"uid":3,"name":"Andersson"}, ]
>>> print(customers) [{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3,
'name': 'Andersson'}] ## Print the uid and name of each customer
>>> for x in customers: print(x["uid"], x["name"]) 1 John 2 Smith 3 Andersson ##
Modify an entry, This will change the name of customer 2 from Smith to Charlie
>>> customers[2]["name"]="charlie"
>>> print(customers) [{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3,
'name': 'charlie'}]
## Add a new field to each entry
>>> for x in customers: x["password"]="123456" # any initial value
>>> print(customers) [{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 2,
'name': 'Smith', 'password': '123456'}, {'uid': 3, 'name': 'charlie', 'password':
'123456'}]
## Delete a field
>>> del customers[1]
>>> print(customers) [{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 3,
'name': 'charlie', 'password': '123456'}]
>>> del customers[1]
>>> print(customers) [{'uid': 1, 'name': 'John', 'password': '123456'}]
## Delete all fields
>>> for x in customers: del x["uid"]
>>> x {'name': 'John', 'password': '123456'} Comprehension: Dictionary
comprehensions can be used to create dictionaries from arbitrary key and value
expressions:
>>> z={x: x**2 for x in (2,4,6)} >>> z {2: 4, 4: 16, 6: 36}
>>> dict11 = {x: x*x for x in range(6)} >>> dict11 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

29

You might also like