Loops
Loops
Range Function
The range function of python generates a list which is special sequence type. A sequence in
python is a succession of values bound together by a single name. Some python sequences
are- strings, lists, tuples etc.
Syntax:
range(start_value(def=0), stop_value(def=nth term), step)
It can accept one, two or three arguments.
If one argument is given then it is assumed to be the stop value. The start value by default is
0. And the step value is 1 by default.
If two arguments are given, these are assumed to be start and stop values, with default step
value of 1.
If three arguments are given, these are read as start, stop and step.
We need to provide three arguments when we are generating a sequence that is in
descending order with or without skipping values. The step value will be negative. Here, the
stop value will be larger than the start value.
Ex:
# Create first 15 multiples of 5.
for i in range(1,16):
print(5*i)
# Even numbers from 100 to 140.
for i in range(100,141):
a=(i%2)
if a == 0:
print(i)
# First 10 whole numbers.
for i in range(1,11):
print(i)
# First 10 natural numbers.
for i in range(0,11):
print(i)
For Loop
The for loop of Python is designed to process any sequence such as a list or a string one by
one.
Syntax:
for <variable> in <sequence (list or string)>:
<statement 1>
<statement n>
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.
Syntax:
list_var = [expression for item in <sequence>]
{ list, string, range() or tuple }
Ex:
i) L1 = [x for x in range(1,11)]
#[1,2…..10]
Assignment 2
1. Generate a list of all the Pythagorean triplets, where x, y, z are values from 1 to 50, using
1 line of code.
2. Generate a list of all alphabets (uppercase & lowercase) using 1 line of code.
Lists are mutable sequences having a progression of elements. We can access the list
elements just by accessing its index values. The individual elements of a list are accessed
through their index values within ‘[ square brackets ]’
Positive: 0 1 2 3 4
L1 = [ ‘a’ , 1 , ‘$’ , 2.7 , -9]
Reverse: -5 -4 -3 -2 -1
Syntaxes:
i. The entire list: list_name
ii. One element: list_name[index_number]
iii. A range of list: list_name[Start: Stop: Step]
Output:
i. L1[1:4]
>>> [1, $]
ii. L1[-1:-4]
Traversing A List
List Mutability
List mutability means that one can change an item present in a list by accessing it directly as part of
the assignment statement. We can modify, update, delete or insert the elements in a list at any
given point of time.
List Slicing
We can extract sub-part of a list using the index values to create list slice.
Syntax:
list_var = [Start: Stop: Step]
Default = 1
Included, Default = 0
Ex:
l = [1,2,3,4,5,6]
print( l [1: 3] )
>>> [2,3]
print( l [ : -1] )
>>> [1,2,3,4,5]
print ( l [ : : 2] )
>>>[1,3,5]
Print ( l [ : : -1] )
>>>[6,5,4,3,2,1]
Nested List
Ex:
>>> 1
>>>’b’
>>> ‘!’
Assignment 3
Assignment 4
1. Create a list containing the first 10 even numbers. Write statements (one statement per
task) for the following:
i. Change elements from index 4 to 9 to first 5 odd numbers.
ii. Add the replaced even numbers to the end of the list.
iii. Remove all the second middle element of the list.
List Operators
List Concatenation
The Concatenation (+), when used with two lists joins two lists. The (+) operator when used with lists
requires that both the operands must be of list types. You cannot add a number or any other value
to a list. Following expression will result into error –
list + string
Ex:
List1 = [ 1,2,3 ]
L3 = List1 + L2
print (L3)
>>> [ 1,2,3,4,5,6,7,8,9 ]
L4 = L1 + 3
Note:
‘+=’ is different from ‘+’ for mutable iterable types such as lists. When ‘+=’ is used with lists then it
requires the operand on the right to be iterable and it will add each element of the iterable to the
register.
Ex:
L1 = [ 1,2,3 ]
L1 = L1 + “abc” #Error
L1 += “abc”
Replication
Ex:
L1 = [ 1,2,3 ]
print (L1 * 3)
>>> [ 1,2,3,1,2,3,1,2,3 ]
Membership Operators
Both ‘in’ and ‘not in’ operators work on lists just like they work for other sequences i.e., ‘in’ tells if an
element is present in the list or not, and ‘not in’ does the opposite.
Ex:
L1 = [ 1,2,3, “apple”]
print ( 2 in L1)
>>> True
>>> True
>>> True
>>> False
>>> True
Comparison Operator
Python internally compares individual elements of lists in a lexicographical order. This means that to
compare equal, each corresponding element must compare equal and the two sequences must be of
the same type i.e., having comparable types of values.
Ex:
L3 = [ 1, [ 2,3 ] ]
L1 == L2
>>> True
L1 == L2
>>> False
Ex:
[ 1, 8, 9, 10 ] < [ 1, 9, 8, 10 ]
>>> True
>>> False
Assignment 5
a) L[1][0::2]
b) ‘A’ in L[1][0]
c) L[1][0::2]
d) L[2::2]
e) L[2][2] in L[1]
Assignment 6
A = [1,2,3]
A[2] = 0
A[A[2]] = 5
A[1:2] = []
2. A = [1,2,[3,4],5]
a. What is the length of A?
b. What are the data types of each element?
c. What does length function of A[2] return?
d. What does A[len(A)] return?
e. What will A[-1*len(A)] return?
List Copy
A list can be truly copied into another list using the following functions-
‘deepcopy’ function is a method that is used to create copies of an object, it provides a deep/
real clone of the object.
Ex:
Import copy
L1 = [1,2,3]
L2 = copy.deepcopy (L1)
L1[0] = ‘apple’
print (L1)
>>> [‘apple’, 2, 3]
print (L2)
>>> [1,2,3]
L2 = copy.deepcopy (L1)
print (L1)
>>> [‘apple’, 2, 3]
print (L2)
L2 = copy.deepcopy (L1)
print (L1)
>>> [‘cat’, 2, 3]
print (L2)
>>> [‘cat’, 2, 3]
Ex:
Import copy
L1 = [1,2,3]
L2 = copy (L1)
L1[0] = ‘apple’
print (L1)
>>> [‘apple’, 2, 3]
print (L2)
>>> [1,2,3]
L2 = copy (L1)
print (L1)
>>> [‘apple’, 2, 3]
print (L2)
L1[0] = ‘cat’
L2 = copy (L1)
print (L1)
>>> [‘cat’, 2, 3]
print (L2)
>>> [‘cat’, 2, 3]
3. Using list()
L1 = [1,2,3]
L2 = list(L1)
print (L2)
>>> [1,2,3]
L1 [0] = ‘a’
print (L1)
>>> [‘a’, 2, 3]
print (L2)
>>> [1, 2, 3]
4. By list slicing
By list slicing we overwrite one or more list elements with one or more other list elements.
We aren’t making a complete copy of the original list, but just a part of it.
Ex:
L1 = [1,2,3]
L2 = L1[1:]
print (L1)
>>> [1,2,3]
print (L2)
>>> [1,2,3]
L1[2]= ‘b’
print [1,2,’b’]
print [1,2,3]
1. del statement
The ‘del’ keyword is used to delete objects. It can delete variables, lists, or a part of a list.
Syntax:
del list
del list[ index_value ]
Ex:
L1 = [1,2,3]
del L1[2]
print (L1)
>>> [1,2]
2. list.clear()
It clears the entire list. However, the variable still stores an empty list. It is a list function.
Ex:
L1.clear()
print (L1)
>>> [ ]
3. list.pop()
It removes an element at a specified index and returns the remove element. If no argument
is given it removes the last element of the list.
Ex:
L1 = [1,2,3]
print (L1)
>>> [ 1,2 ]
print (L1)
>>> [2]
The pop() raises an exception if the list is already empty. It will throw an index error.
4. list.remove()
The remove method removes the first occurrence of given item from the list. It takes one
essential argument and does not return anything. It will report an error if there is no such
item in the list (value error).
NOTE: The pop method removes an individual element and returns it, while remove()
searches for an item and removes the first matching item from the list.
Ex:
L1.remove(‘p’)
print (L1)
A list can be added only to another list. We can combine two lists using the ‘+’ operator,
known as ‘List Concatenation’
Ex:
L1 = [1,2,3]
L1 += [4]
print(L1)
>>> [1,2,3,4]
2. list.append()
This method adds an item to the end of the list. It takes exactly one element and does not
return the new list, just modifies the original.
Ex:
L1 = [1,2,3]
L1.append(4)
print (L1)
>>> [1,2,3,4]
L1.append ([5,6])
print (L1)
>>> [1,2,3,4,[5,6] ]
Nested list
Notice, when you try appending a list it adds the element as a nested list to the original list.
3. list.extend()
The extend function is used for adding multiple elements. It takes exactly one element or
elements as a list type and does not return the new list, just modifies the original list.
Ex:
L1 = [1,2]
L1.extend(3)
print(L1)
>>> [1,2,3]
L1.extend([4,5,6])
print(L1)
>>> [1,2,3,4,5,6]
List itself.
4. list.insert()
The insert () inserts an item at a given position. It takes two arguments and does not return a
new list, just modifies the original. If index is less than 0 and not equal to any of the valid
negative indexes of the list the object will prepend i.e., adding at the beginning of the list.
Ex:
L1.insert(2, ‘i' )
print(L1)
1. len()
It returns the length of its argument list i.e., it returns the number of elements passed in the
list.
Ex:
L1 = [1,2,3]
print (len(L1))
>>> 3
2. count(element)
This function returns the count of the item that you passed as an argument. If the given item
is not in the list it returns 0.
Ex:
print (L1.count(‘p’))
>>> 2
3. index(element)
This function returns the index of first matched item from the list. If the given item is not in
the list it raises value error exeception.
Ex:
l1
>>> [1, 2, 3]
l1.index(2)
>>> 1
4. reverse()
This function reverses the items of the list. This is done “in place” i.e., it does not create a
new list, but modifies the original and does not return anything.
Ex:
L1 = [1,2, ‘apple’]
L1.reverse()
print (L1)
>>> [‘apple’, 2, 1]
5. sort()
This function sorts the items of the list, by default in increasing order. This is done “in place”
i.e., it does not create a new list, but modifies the original and does not return anything.
Ex:
L1 = [80, 1, 5 ,3]
L1.sort()
print(L1)
>>> [1,3,5,80]
L2.sort()
print (L2)
list.sort(reverse = True)
6. sorted ()
This function takes the name of the list as an argument and returns a new sorted list with
sorted elements in it.
Ex:
L1 = [71,10,96,5]
L2 = sorted(L1)
print (L2)
>>> [5,10,71,96]
7. sum()
Ex:
L1 = [1,2,3]
print (sum(L1))
>>> 6
8. max()
Ex:
L = [1,2,3]
print (max(L))
>>> 3
9. min()
Ex:
L = [1,2,3]
print (min(L))
>>> 1
Sort vs Sorted
SORT SORTED
1. It modifies the list; it is called on. i.e., the It creates a new list containing a sorted version of
sorted list is stored in the same list; a new list a list passed to it as argument. It does not modify
is not created. the original list.
2. It works on the list and modifies it. It takes any iterable sequence, such as a list or a
tuple etc. And it always returns a sorted list
irrespective of the type of the sequence passed
to it.
3. It doesn’t return anything. It returns the newly created sorted list.
Tuples
1. A tuple is standard data type that can store a sequence of values belonging to any type.
2. Tuples are immutable i.e.; you cannot change the elements of a tuple in place.
3. The elements of a tuple are enclosed within common brackets.
4. Each element occupies sequential memory location.
Creating Tuples
1. tuple ()
Ex:
T1 = () #Empty Tuple
>>> tuple
>>> int
T1 = (7,)
>>> tuple
#Using tuple ()
T2 = tuple ([1,2,3])
print (T2)
>>> (1,2,3)
Accessing Tuples
Tuples are immutable sequences having a progression of elements. Thus, other than editing items,
you can do all that you can do with a list. We cannot access an individual element of a tuple.
#Slicing
print (T1[ 2: ])
Tuple Operator
Ex:
T1 = (1,2,3)
T2 = (4,5,6)
T = T1 + T2
print (T)
>>> (1,2,3,4,5,6)
2. Replication ‘*’
Ex:
T1 = (1,2,3)
print (T1*3)
>>> (1,2,3,1,2,3,1,2,3)
3. Membership Operator
Ex:
T1 = (1,2,3)
print (4 in T1)
>>> False
>>> True
4. Comparison
Ex:
T1 = (1,2,3)
T2 = (4,5,6)
>>> False
print ( T1 == T2)
>>> False
>>> True
Creating a tuple from a set of values is called Packing and creating individual values from a
tuple’s elements is called unpacking.
Note: Tuple Unpacking requires that the list of variables on the left has the same number of
elements as the length of the tuples.
Ex:
#Packing
print (type(T1))
T1 = (1,2,3)
L1 = list(T1)
L1 [1] = ‘cat’
T1 = tuple(L1)
print (T1)
6. Deleting Tuples
The del statement of Python is used to delete elements and objects but as you know the
tuples are immutable, which also means that individual elements of a tuple cannot be
deleted.
Ex:
#del statement
T1 = (1,2,3)
del T1
print (T1)
t2
T1 = (1,2,3)
L1 = list(T1)
del (L1[0])
print (T1)
>>> (2,3)_
a, b = T1
T1 = b
print (T1)
>>> (3,)
Built-in Functions
1. id (tuple)
2. len ()
3. max (tuple)
This function returns the elements from the tuple having maximum value.
4. min (tuple)
This function returns the elements from the tuple having minimum value.
5. sum (tuple)
This function takes the tuple sequence and returns the sum of the elements of the tuple.
This function takes the name of the tuple as an argument and returns a new sorted list with
sorted elements in it.
7. tuple.index(element)
returns the index value of the entered element of a tuple and only the first occurrence.
8. tuple.count(element)