[go: up one dir, main page]

0% found this document useful (0 votes)
23 views35 pages

Python Unit 2

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

Python Unit 2

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

2

CONTROL STRUCTURES
2.1 BOOLEAN EXPRESSIONS
2.1.1 Boolean Values
The Boolean values are True and False. The relational operators such as = = , !=, > ,
< , >= , <= and the logical operators such as and, or, not are the Boolean operators. The
statement that prints either true or false is a Boolean expression. The following examples use
the operator !=, which compares two operands and produces ‘True’ if they are not equal and
‘False’ otherwise:
>>> 5 != 5 True
>>> 5 !=6 False
So, ‘True’ and ‘False’ are special values which belong to the Boolean type; they are
not strings (case sensitive):
Python has a data type called boolean, which can take two possible values, True and
False. Most functions that answer a yes/no question (or a true/false situation) will return a
boolean answer.
An expression that evaluates to a true/false value is called a Boolean expression.
BooleanExpressions are used mostly in control structures for testing a condition is true or
false.
Example:
1. print( True and True ) # prints True
2. print( True and False ) # prints False
3. print( 3 < 4 and 10 < 12 ) # prints True
2.2 Control Structures

4. print( 3 < 4 or 12 < 10 ) # prints True


5. print( 4 < 3 or 12 < 10 ) # prints False
6. print( (4 < 3 and 12 < 10) or 7 == 7 ) # prints True
2.1.2 Relational Operators
The relational operators in Python perform the usual comparison operations, shown in
Figure 2.1. Relational expressions are a type of Boolean expression, since they evaluate to a
Boolean result. These operators not only apply to numeric values, but to any set of values that
has an ordering, such as strings.

Fig : 2.1 Relational Operators


2.1.3 Membership Operators
Python provides a convenient pair of membership operators . These operators can be
used to easily determine if a particular value occurs within a specified list of values. The
membership operators are given in Figure 2.2.
The in operator is used to determine if a specific value is in a given list, returning
True if found, and False otherwise. The not in operator returns the opposite result

Fig:2.2 : Membership Operators


Python 2.3

2.1.4 Boolean Operators


George Boole, in the mid-1800s, developed what we now call Boolean algebra . His
goal was todevelop an algebra based on true/false rather than numerical values. Boolean
algebra contains aset of Boolean ( logical ) operators , denoted by and, or, and not in Python.
These logical operatorscan be used to construct arbitrarily complex Boolean expressions. The
Boolean operators are shown in Figure 2.3.
Logical and is true only when both its operands are true—otherwise, it is false. Logical
or istrue when either or both of its operands are true, and thus false only when both operands
are false.Logical not simply reverses truth values—not False equals True, and not True equals
False.

Fig 2.3 Boolean Logic Truth Table

2.2 SELECTION CONTROL


2.2.1 What is a Control Structure?
Control flow is the order that instructions are executed in a program. A control
statement is a statement that determines the control fl ow of a set of instructions. There are
three fundamental forms of control that programming languages provide— sequential control
, selection control , and iterative control.
Sequential control: Default mode. Sequential execution of code statements (one line after
another) -- like following a recipe
Selection Control: Used for decisions, branching -- choosing between 2 or more alternative
paths. In Python, these are the types of selection statements:
1. if
2. if-else
3. if-elif-else
2.4 Control Structures

Iterative Control: Used for looping, i.e. repeating a piece of code multiple times in a row. In
Python, there are three types of loops:
1. While Loop
2. For Loop

2.3 IF STATEMENT
Syntax:
If test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if
the text expression is True. If the text expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the indentation. Body starts with
an indentation and the first unindented line marks the end.
Flow Chart:

Example program:
# If the number is positive, we print an appropriate message
num = 3
if num > 0:
Python 2.5

print(num, "is a positive number.")


print("This is always printed.")
Output :
3 is a positive number
This is always printed
2.3.1 if...else Statement:
Syntax :
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.
Flow Chart:

Example Program:
#Program checks if the number is positive or negative and displays an appropriate
message
num =- 3
if num >= 0:
2.6 Control Structures

print("Positive Number")
else:
print("Negative Number")
Output:
Negative Number
2.4 MULTIWAY SELECTION :
2.4.1 if...elif...else Statement
Syntax :
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
It allows us to check for multiple expressions. If the condition for if is False, it checks
the condition of the next elif block and so on. If all the conditions are False, body of else is
executed. The elif is short for else if. Only one block among the several if...elif...else blocks
is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.
Flowchart :
Python 2.7

Example Program:
# Python program to find the largest number among the three input numbers
a = int(input(“Enter first number: “))
b = int(input(“Enter second number:))
c = int(input(“Enter third number: ))
if (a > b) and (a > c):
largest = a
elif (b > a) and b>c):
largest = b
else:
largest=c
print(“The largest number between”,a,”,”,b,”and”,c,”is”,largest)
Output:
Enter first number: 4
Enter second number: 56
Enter third number: 6
(‘The largest number between’, 4.0, ‘,’, 56.0, ‘and’, 6.0, ‘is’, 56.0)
2.4.2 Nested if statements :
We can have a if...elif...else statement inside another if...elif...else statement. This is
called nesting in computer programming. Any number of these statements can be nested
inside one another. Indentation is the only way to figure out the level of nesting.
The structure of nested conditionals is shown below.
if test expression:
Body of if
else:
if test expression:
Body of if
else:
if test expression:
2.8 Control Structures

Body of if
:
:
else:
Body of else
The following programs explain nested conditional.
# Program to compare the values of x and y
x=3
y=4
if x == y:
print ‘x and y are equal’
else:
if x < y:
print ‘x is less than y’
else:
print ‘x is greater than y’
In this program the variables x and y are assigned with values 3 and 4 respectively. In
the first If statement it checks whether x is equal to y. If it is true, then prints x and y are
equal. If it is false, it executes the else part. Here, the else part contains the if statement
( Nested if ) checks whether x is lesser than y. If it is true, then it prints x is less than y. If it is
false, then it prints x is greater than y that is the statement in else part.
2.5 INDENTATION IN PYTHON :
Indentation in Python refers to the (spaces and tabs) that are used at the beginning of a
statement. The statements with the same indentation belong to the same group called a suite.
Consider the example of a correctly indented Python code statement mentioned below.
a = input('Enter the easiest programming language: ') //statement 1
if a == 'python': //statement 2
print('Yes! You are right') //statement 3
else: //statement 4
print('Nope! You are wrong') //statement 5
Python 2.9

In the above code,

Statement 1 gets executed first, then it gets to statement 2. Now only if statement 2 is
correct, we would want statement 3 to get printed. Hence Statement 3 is indented with 2
spaces. Also, statement 5 should be printed, if statement 4 is true and hence this is also
indented with 2 spaces. Statement 1, 2 and 4 are main statements which need to be checked
and hence these 3 are indented with the same space.

2.6 ITERATIVE CONTROLS:

Iteration means executing the same block of code over and over, potentially many
times. A programming structure that implements iteration is called a loop. Iteration statements
or loop statements allow us to execute a block of statements as long as the condition is true.
Loops statements are used when we need to run same code again and again, each time with a
different value.

In programming, there are two types of iteration, indefinite and definite: With
indefinite iteration, the number of times the loop is executed isn’t specified explicitly in
advance. Rather, the designated block is executed repeatedly as long as some condition is met.

With definite iteration, the number of times the designated block will be executed is
specified explicitly at the time the loop starts.

2.6.1 Definite Vs Indefinite Loops

A definite loop is a loop in which the number of times it is going to execute is known
in advance before entering the loop, while an indefinite loop is executed until some condition
is satisfied and the number of times it is going to execute is not known in advance. Often,
definite loops are implemented using for loops and indefinite loops are implemented using
while loops and do-while loops. But there is no theoretical reason for not using for loops for
indefinite loops and while loops for definite loops. But indefinite loops could be neatly
organized with while loops, while definite loops could be neatly organized with for loops.

In Python Iteration (Loops) statements are of three type :-

1. While Loop

2. For Loop

3. Nested For Loops


2.10 Control Structures

2.7 WHILE LOOP

A while loop statement in Python programming language repeatedly executes a


target statement as long as a given condition is true.
Syntax:

while <expression>:
statement(s)
Here, statement(s) may be a single statement or a block of statements. The
condition may be any expression, and true is any non-zero value. The loop iterates while the
condition is true.

When the condition becomes false, program control passes to the line immediately
following the loop.

In Python, all the statements indented by the same number of character spaces
after a programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.

Here, key point of the while loop is that the loop might not ever run. When the
condition is tested and the result is false, the loop body will be skipped and the first statement
after the While loop will be executed.

Flow Chart:
Python 2.11

Example Program :
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
Output:
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
The block here, consisting of the print and increment statements, is executed
repeatedly until count is no longer less than 9. With each iteration, the current value of the
index count is displayed and then increased by 1.
2.7.2 The Infinite While Loop
A loop becomes infinite loop if a condition never becomes FALSE. You must use
caution when using while loops because of the possibility that this condition never resolves to
a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the server needs
to run continuously so that client programs can communicate with it as and when required.
Example Program:
var = 1
while var == 1 : # This constructs an infinite loop
2.12 Control Structures

num = raw_input("Enter a number :")


print "You entered: ", num
print "Good bye!"
Output:
Enter a number :20
You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Above example goes in an infinite loop and you need to use CTRL+C to exit the
program.
2.7.3 Using else Statement with Loops
Python supports to have an else statement associated with a loop statement.If the else
statement is used with a while loop, the else statement is executed when the condition
becomes false.
The following example illustrates the combination of an else statement with a while
statement that prints a number as long as it is less than 5, otherwise else statement gets
executed.
Example Program:
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
Output:
0 is less than 5
1 is less than 5
2 is less than 5
Python 2.13

3 is less than 5
4 is less than 5
5 is not less than 5
Single Statement Suites
Similar to the if statement syntax, if your while clause consists only of a single
statement, it may be placed on the same line as the while header.
Here is the syntax and example of a one-line while clause −
flag = 1
while (flag):
print 'Given flag is really true!'
print "Good bye!"
It is better not try above example because it goes into infinite loop and you need to
press CTRL+C keys to exit.
2.8 DEFINITE LOOP
2.8.1 For Loop
For loop in Python is used to iterate over items of any sequence, such as a list or a
string.
Syntax
for val in sequence:
statements
Flowchart
2.14 Control Structures

Example Program:
for I in range(1,5):
print(i)
Output :-
1
2
3
4
The range() Function:
The range() function is a built-in that is used to iterate over a sequence of numbers.
Syntax :
range(start, stop[, step])
The range() Function Parameters :
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step(Optional): Determines the increment between each numbers in the sequence.
Example 1 of range() function
Python 2.15

for i in range(5):
print(i)
Output :-
0
1
2
3
4
Example 2 of range() function
for i in range(2,8):
print(i)
Output :-
2
3
4
5
6
7
Example 3 of range() function using step parameter
for i in range(2,9,2):
print(i)
Output :-
2
4
6
8
Example 4 of range() function
2.16 Control Structures

for i in range(0,-10,-2):
print(i)
Output :-
0
-2
-4
-6
-8
2.8.2 For Loop With Else :
The else is an optional block that can be used with for loop.The else block with for
loop executed only if for loops terminates normally.This means that the loop did not
encounter any break.
Example of For Loop With Else
list=[2,3,4,6,7]
for i in range(0,len(list)):
if(list[i]==5):
print('list has 5')
break
else:
print('list does not have 5')
Output :-
list does not have 5
2.8.3 Nested For Loops
When one Loop defined within another Loop is called Nested Loops.
Syntax of Nested For Loops
for val in sequence:
for val in sequence:
statements
Python 2.17

statements
Example 1 of Nested For Loops (Pattern Programs)
for i in range(1,6):
for j in range(0,i):
print(i, end=" ")
print('')
Output :-
1
22
333
4444
55555
Example 2 of Nested For Loops (Pattern Programs)
for i in range(1,6):
for j in range(5,i-1,-1):
print(i, end=" ")
print('')
Output :-
11111
2222
333
44
5
2.8.4 Loop Control Statements
Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed. Python
supports the following control statements.

Control Statement Description


2.18 Control Structures

break statement It terminates or breaks the loop statement and


transfers flow of execution to the statement
immediately following the loop.

continue statement Causes the loop to skip the rest of its body
and immediately retest its condition before
reiterating.

pass statement The pass statement in Python is used when a


statement is required syntactically but you do
not want any command or code to execute.

Break statement
The break statement is used to change or alter the flow of execution. The looping
statements iterates till the test expression is true. In some cases, the current iteration of the
loop need to be terminated. The break statement is used in this case. The break statement
terminates the loop containing it. Therefore, control of the program transfers to the statement
immediately after the body of the loop. If break statement is used inside a nested loop (loop
inside another loop), break will terminate the innermost loop.
Syntax of break Statement
break
Flowchart:

Example 1 of break statement


for i in range(10):
Python 2.19

print(i)
if(i == 7):
print('break')
break
Output :-
0
1
2
3
4
5
6
7
break
Example 2 of break statement

After break statement controls goes to next line pointing after the loop body.

for i in range(10):

print(i)

if(i == 7):

print('before break')

break

print('after break') # Inside loop body, any code after the break statement will not
execute

print('Out of loop body')

Output :-
0

2
2.20 Control Structures

7
before break
Out of loop body
Continue Statement:
Continue Statement in Python is used to skip all the remaining statements in the
loop and move controls back to the top of the loop.
Syntax of Continue Statement
continue
Flowchart of Continue Statement

Example of Continue statement


for i in range(6):
if(i==3):
continue
Python 2.21

print(i)
Output :-
0
1
2
4
5
when 'i' is equal to 3 continue statement will be executed which skip the print statement.
Pass Statement:
Pass Statement in Python does nothing. You use pass statement when you create a
method that you don't want to implement, yet.
Example using Pass Statement
It makes a controller to pass by without executing any code.
def myMethod():
pass
print('hello')
Output :-
hello
Example without using pass statement
def myMethod():
print('hello')
Output :-
Traceback (most recent call last):
File "python", line 3
print('hello')
Indentation Error: expected an indented block
Difference Between Pass And Continue Statement in Python
Pass statement simply does nothing. You use pass statement when you create a method
that you don't want to implement, yet.
2.22 Control Structures

Where continue statement skip all the remaining statements in the loop and move
controls back to the top of the loop.
Example of difference between pass and continue statement
for i in 'hello':
if(i == 'e'):
print('pass executed')
pass
print(i)
print('----')
for i in 'hello':
if(i == 'e'):
print('continue executed')
continue
print(i)

Output :-
h
pass executed
e
l
l
o
----
h
continue executed
l
l
o
2.9 LISTS
In Python, a list is a collection of ordered and indexed elements of different data types.
In Python, the list and its elements are mutable. That means, the list and its elements can be
Python 2.23

modified at any time in the program. In Python, the list data type (data structure) has
implemented with a class known as a list. All the elements of a list must be enclosed in square
brackets, and each element must be separated with a comma symbol. In Python, the list
elements are organized as an array of elements of different data types. All the elements of a
list are ordered and they are indexed. Here, the index starts from '0' (zero) and ends with
'number of elements - 1'.
In Python, the list elements are also indexed with negative numbers from the last
element to the first element in the list. Here, the negative index begins with -1 at the last
element and decreased by one for each element from the last element to the first element.
A list is a data type that allows you to store various types data in it. List is a compound
data type which means you can have different-2 data types under a list, for example we can
have integer, float and string items in a same list.
2.9.1. Create a List in Python
Lets see how to create a list in Python. To create a list all you have to do is to place the
items inside a square bracket [] separated by comma ,.
# list of floats
num_list = [11.22, 9.9, 78.34, 12.0]
# list of int, float and strings
mix_list = [1.13, 2, 5, "beginnersbook", 100, "hi"]
# an empty list
nodata_list = []
As we have seen above, a list can have data items of same type or different types. This
is the reason list comes under compound data type.
2.9.2 Accessing the items of a list
Syntax to access the list items:
list_name[index]
Example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]

# prints 11
print(numbers[0])

# prints 300
print(numbers[5])
2.24 Control Structures

# prints 22
print(numbers[1])
Output:
11
300
22
Points to Note:
1. The index cannot be a float number.
For example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# error
print(numbers[1.0])
Output:
TypeError: list indices must be integers or slices, not float
2. The index must be in range to avoid IndexError. The range of the index of a list having 10
elements is 0 to 9, if we go beyond 9 then we will get IndexError. However if we go
below 0 then it would not cause issue in certain cases, we will discuss that in our next
section.
For example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# error
print(numbers[6])
Output:
IndexError: list index out of range
2.9.3. Negative Index to access the list items from the end
Unlike other programming languages where negative index may cause issue, Python
allows you to use negative indexes. The idea behind this to allow you to access the list
elements starting from the end. For example an index of -1 would access the last element of
the list, -2 second last, -3 third last and so on.
Example of Negative indexes in Python
Python 2.25

# a list of strings
my_list = ["hello", "world", "hi", "bye"]
# prints "bye"
print(my_list[-1])
# prints "world"
print(my_list[-3])
# prints "hello"
print(my_list[-4])
Output:
bye
world
hello
2.9.4. How to get a sublist in Python using slicing?
We can get a sublist from a list in Python using slicing operation. Lets say we have a
list n_list having 10 elements, then we can slice this list using colon : operator. Lets take an
example to understand this:
Slicing example
# list of numbers
n_list = [1, 2, 3, 4, 5, 6, 7]
# list items from 2nd to 3rd
print(n_list[1:3])
# list items from beginning to 3rd
print(n_list[:3])
# list items from 4th to end of list
print(n_list[3:])
# Whole list
print(n_list[:])
Output:
[2, 3]
[1, 2, 3]
[4, 5, 6, 7]
2.26 Control Structures

[1, 2, 3, 4, 5, 6, 7]
2.9.5. List Operations
There are various operations that we can perform on Lists.
2.9.5.1 Addition
There are several ways you can add elements to a list.
# list of numbers
n_list = [1, 2, 3, 4]
# 1. adding item at the desired location
# adding element 100 at the fourth location
n_list.insert(3, 100)
# list: [1, 2, 3, 100, 4]
print(n_list)

# 2. adding element at the end of the list


n_list.append(99)
# list: [1, 2, 3, 100, 4, 99]
print(n_list)
# 3. adding several elements at the end of list
# the following statement can also be written like this:
# n_list + [11, 22]
n_list.extend([11, 22])
# list: [1, 2, 3, 100, 4, 99, 11, 22]
print(n_list)
Output:
[1, 2, 3, 100, 4]
[1, 2, 3, 100, 4, 99]
[1, 2, 3, 100, 4, 99, 11, 22]
2.9.5.2 Update elements
We can change the values of elements in a List. Lets take an example to understand this:
Python 2.27

# list of numbers
n_list = [1, 2, 3, 4]
# Changing the value of 3rd item
n_list[2] = 100
# list: [1, 2, 100, 4]
print(n_list)
# Changing the values of 2nd to fourth items
n_list[1:4] = [11, 22, 33]
# list: [1, 11, 22, 33]
print(n_list)
Output:
[1, 2, 100, 4]
[1, 11, 22, 33]

2.9.5.3 Delete Elements


# list of numbers
n_list = [1, 2, 3, 4, 5, 6]

# Deleting 2nd element


del n_list[1]
# list: [1, 3, 4, 5, 6]
print(n_list)
# Deleting elements from 3rd to 4th
del n_list[2:4]
# list: [1, 3, 6]
print(n_list)
# Deleting the whole list
del n_list
Output:
2.28 Control Structures

[1, 3, 4, 5, 6]
[1, 3, 6]
2.9.5.4 Deleting elements using remove(), pop() and clear() methods
remove(item): Removes specified item from list.
pop(index): Removes the element from the given index.
pop(): Removes the last element.
clear(): Removes all the elements from the list.
# list of chars
ch_list = ['A', 'F', 'B', 'Z', 'O', 'L']
# Deleting the element with value 'B'
ch_list.remove('B')
# list: ['A', 'F', 'Z', 'O', 'L']
print(ch_list)
# Deleting 2nd element
ch_list.pop(1)
# list: ['A', 'Z', 'O', 'L']
print(ch_list)
# Deleting all the elements
ch_list.clear()
# list: []
print(ch_list)
Output:
['A', 'F', 'Z', 'O', 'L']
['A', 'Z', 'O', 'L']
[]
Built-in List Functions & Methods :
Python includes the following list functions :

Sr.No
Function with Description
.
1 cmp(list1, list2) Compares elements of both lists.
Python 2.29

2 len(list) Gives the total length of the list.


3 max(list) Returns item from the list with max value.
4 min(list) Returns item from the list with min value.
5 list(seq) Converts a tuple into list.

Python includes following list methods

Sr.No Methods with Description


.
1 list.append(obj) Appends object obj to list
2 list.count(obj) Returns count of how many times obj occurs in
list
3 list.extend(seq) Appends the contents of seq to list
4 list.index(obj) Returns the lowest index in list that obj appears
5 list.insert(index,obj) Inserts object obj into list at offset index
6 list.pop(obj=list[-1]) Removes and returns last object or obj from list
7 list.remove(obj) Removes object obj from list
8 list.reverse() Reverses objects of list in place
9 list.sort([func]) Sorts objects of list, use compare func if given

2.10 ITERATING OVER LISTS


2.10.1 Iterate through list using range() method
The range() function generates the sequence of integers from the start value till the
end/stop value, but it doesn’t include the end value in the sequence i.e. it doesn’t include the
stop number/value in the resultant sequence.
Example:
lst =[10, 50, 75, 83, 98, 84, 32]
forx inrange(len(lst)):
print(lst[x])
In the above code, the list is iterated using range() function which traverses
through 0(zero) to the length of the list defined.
2.30 Control Structures

Output:
10
50
75
83
98
84
32
2.10.2 Iterate through list in Python using a for Loop
Python for loop can be used to iterate through the list directly.
Syntax:
for var_name in input_list_name:
Example:
lst =[10, 50, 75, 83, 98, 84, 32]
forx inlst:
print(x)
Output:
10
50
75
83
98
84
32
2.10.3. List Comprehension to iterate through a list in Python
Python list comprehension is an indifferent way of generating a list of elements that
possess a specific property or specification i.e. it can identify whether the input is a list, string,
tuple, etc.
Python 2.31

Syntax:
expression/statement for item in input_list]
Example:
lst = [10, 50, 75, 83, 98, 84, 32]
[print(x) for x in lst]
Output:
10
50
75
83
98
84
32
2.10.4. Iterate through list in Python with a while loop
Python while loop can also be used to iterate the list in a similar fashion as that of for
loops.

Syntax:
while(condition) :
Statement
update_expression
Example:
lst = [10, 50, 75, 83, 98, 84, 32]
x=0
# Iterating using while loop
while x < len(lst):
print(lst[x])
2.32 Control Structures

x = x+1
Output:
10
50
75
83
98
84
32
2.10.5. Python NumPy to iterate through List in Python
Python NumPy can also be used to iterate a list efficiently.
Python numpy.arrange() function creates a uniform sequence of integers.

Syntax for numpy.arange() function:


numpy.arange(start, stop, step)
 start: This parameter is used to provide the starting value/index for the sequence of
integers to be generated.
 stop: This parameter is used to provide the end value/index for the sequence of
integers to be generated.
 step: It provides the difference between each integer from the sequence to be
generated.
The numpy.nditer(numpy_array) is a function that provides us with an
iterator to traverse through the NumPy array.
Example:
import numpy as np
n = np.arange(16)
for x in np.nditer(n):
print(x)
Python 2.33

In the above code, np.arange(16) creates a sequence of integers from 0 to 15.


Output:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2.10.6. Python enumerate() method to iterate a Python list
Python enumerate() function can be used to iterate the list in an optimized manner.
The enumerate() function adds a counter to the list or any other iterable and
returns it as an enumerate object by the function.
Thus, it reduces the overhead of keeping a count of the elements while the
iteration operation.
Syntax:
enumerate(iterable, start_index)
 start_index: It is the index of the element from which the counter has to be recorded
for the iterating iterable.
Example:
2.34 Control Structures

lst = [10, 50, 75, 83, 98, 84, 32]


for x, res in enumerate(lst):
print (x,":",res)
Output:
0 : 10
1 : 50
2 : 75
3 : 83
4 : 98
5 : 84
6 : 32

2.10.7 Iterating a Python list using lambda function


Python’s lambda functions are basically anonymous functions.
Syntax:
lambda arguments: Expression
 Expression: The iterable which is to be evaluated.
The lambda function along with a Python map() function can be used to
iterate a list easily.
Python map() method accepts a function as a parameter and returns a
list.
The input function to the map() method gets called with every element
of the iterable and it returns a new list with all the elements returned from the
function, respectively.
Example:
lst = [10, 50, 75, 83, 98, 84, 32]
res = list(map(lambda x:x, lst))
print(res)
Python 2.35

In the above of code, lambda x:x function is provided as input to the map()
function. The lambda x:x will accept every element of the iterable and return it.
The input_list (lst) is provided as the second argument to the map() function.
So, the map() function will pass every element of lst to the lambda x:x function and
return the elements.
Output:
[10, 50, 75, 83, 98, 84, 32]

You might also like