0% found this document useful (0 votes)
20 views23 pages

Loops

The document provides an overview of loops in Python, focusing on the range function, for loops, and list comprehensions. It includes syntax examples and practical use cases for generating sequences, accessing and modifying lists, and performing list operations. Additionally, it outlines assignments related to list manipulation and operators, as well as methods for copying lists.

Uploaded by

pranavrao168
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)
20 views23 pages

Loops

The document provides an overview of loops in Python, focusing on the range function, for loops, and list comprehensions. It includes syntax examples and practical use cases for generating sequences, accessing and modifying lists, and performing list operations. Additionally, it outlines assignments related to list manipulation and operators, as well as methods for copying lists.

Uploaded by

pranavrao168
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/ 23

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)

# Odd numbers from 220 to 200 in descending order.


for i in range(220,199,-2):
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]

ii) fruits =['apple', 'banana', 'kiwi']


l1= [x for x in fruits if 'a' in x]
iii) l2 = [x for x in range(1,11) if x%5==0 and x%50==0]

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.

l1 = [[x,y,z] for x in range(1,51) for y in range(1,51) for z in range(1,51) if (x**2 + y**2 ==


z**2)]
[[3, 4, 5], [4, 3, 5], [5, 12, 13], [6, 8, 10], [7, 24, 25], [8, 6, 10], [8, 15, 17], [9, 12, 15], [9, 40,
41], [10, 24, 26], [12, 5, 13], [12, 9, 15], [12, 16, 20], [12, 35, 37], [14, 48, 50], [15, 8, 17],
[15, 20, 25], [15, 36, 39], [16, 12, 20], [16, 30, 34], [18, 24, 30], [20, 15, 25], [20, 21, 29],
[21, 20, 29], [21, 28, 35], [24, 7, 25], [24, 10, 26], [24, 18, 30], [24, 32, 40], [27, 36, 45],
[28, 21, 35], [30, 16, 34], [30, 40, 50], [32, 24, 40], [35, 12, 37], [36, 15, 39], [36, 27, 45],
[40, 9, 41], [40, 30, 50], [48, 14, 50]]

2. Generate a list of all alphabets (uppercase & lowercase) using 1 line of code.

Advantages of List Comprehension

 Reduction in the number of lines of code.


 List comprehensions are faster as python will allocate the list memory first before
adding the elements to it instead of resizing it during run time.
Accessing List

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

Traversal of a sequence means accessing and processing each element of it.


Ex:
l1 = [21,22,23]
for j in l1:
print(j)
>>> 21
22
23

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

Excluded, Default = nth term

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

A list inside a list is called a Nested List.

Ex:

L = [ 1, 2, [ ‘a’ , ‘b’ ], [ ‘$’, ‘!’ ] ]

>>> print( L[0] )

>>> 1

>>> print( L[2][1] )

>>>’b’

>>> print( L[3][1] )

>>> ‘!’
Assignment 3

1. What are the different ways to create a list?


2. What type of values can be included in a python list?
3. How can these lists be created using range function:
i) [ 4, 5, 6 ]
ii) [ -2,1,3 ]
iii) [ -9, -8 , -7, -6, -5, -4, -3 ]
iv) [ -9, -10, -11, -12 ]
4. If a = [ 5, 4, 3, 2, 1, 0 ], evaluate the following expressions:
i. a[-1]
ii. a[a[0]]
iii. a[a[-1]]
iv. a[ a[ a[ a[2]+1 ] ] ]

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 + number (int & float)

list + complex_number (2a, 5j)

list + string

Ex:

List1 = [ 1,2,3 ]

List1 = List 1 + [4]


L2 = [ 5,6,7,8,9 ]

L3 = List1 + L2

print (L3)

>>> [ 1,2,3,4,5,6,7,8,9 ]

L4 = L1 + 3

Type Error: Cannot concatenate list with ‘int’

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”

print (L1) = [ 1,2,3, ‘a’, ‘b’, ‘c’ ]

Replication

(*) is used to replicate a list specific number of times.

Ex:

L1 = [ 1,2,3 ]

print (L1 * 3)

>>> [ 1,2,3,1,2,3,1,2,3 ]

Membership Operators

‘in’ and ‘not in’

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

print ( “a” in L1)

>>> True

print ( 5 not in L1)

>>> True

print ( “e” in L1[3] )

>>> False

print ( “a” in L1[3] )

>>> 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:

L1, L2 = [ 1,2,3 ],[ 1,2,3 ]

L3 = [ 1, [ 2,3 ] ]

L1 == L2

>>> True

L1 == L2

>>> False

Ex:

[ 1,2,3 ] > [ 1,2,1 ]

>>> True ( Lexicography )

[ 1, 8, 9, 10 ] < [ 1, 9, 8, 10 ]

>>> True

[ 1, [1,2 ] ] > [ 8,9 ]

>>> False
Assignment 5

1. What is a [1:1], if ‘a’ is string of at least two characters?


2. What is a [ 1:1], if ‘a’ is list with one element?
3. What do these expressions evaluate to if –
L = [ “These”, [“are”, “a”, “few”, “words”], “that, ‘’ we’’, “use”, “?” ]

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]

4. L = [ ‘p’, ‘r’, ‘o’, ‘b’, ‘l’, ‘e’, ‘m’]


a. L[2:3] = []
Print(L)
b. L[2:5] = []
Print(L)

Assignment 6

1. Consider the following code. What is the value of A at the end?

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?

3. Using the same list of question 2, after this statement –


A[1:2] = [[2,3], 4]. Answer these questions –

a. What is the length of ‘A’.


b. What does len(A[1] + A[3]) return?
Assignment 7

1) Write a program to reverse the elements in a loop using for loop.


2) Write a program to merge two lists using for loop.
3) Write a program that accepts a list of numbers from the user and replaces all numbers
greater than 20 with 5
4) Find the maximum, minimum, mean of numerical values in a list. [Lab Program]

List Copy

A list can be truly copied into another list using the following functions-

1. Using copy module_deepcopy

‘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)

>>> [‘apple’, 2,3]


L1[0] = ‘cat’

L2 = copy.deepcopy (L1)

print (L1)

>>> [‘cat’, 2, 3]

print (L2)

>>> [‘cat’, 2, 3]

2. copy() allows you to create a true copy of a list. It is a list function.

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)

>>> [‘apple’, 2,3]

L1[0] = ‘cat’

L2 = copy (L1)

print (L1)

>>> [‘cat’, 2, 3]

print (L2)

>>> [‘cat’, 2, 3]

3. Using list()

The list function type casts into list data type.


Ex:

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]

Removing Elements in a list

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]

L1.pop ( )  { pops last element }

print (L1)

>>> [ 1,2 ]

L1.pop (0)  { pops index value }

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 = [‘a’, ‘p’, ‘p’, ‘l’, ‘e’]

L1.remove(‘p’)

print (L1)

>>> [‘a’, ‘p’, ‘l’, ‘e’]

Adding Elements to the List

1. Using List Concatenation

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.

Syntax: list.insert(index, element)

Ex:

L1 = [‘a’, ‘e’, ‘u’]

L1.insert(2, ‘i' )

print(L1)

>>> [‘a’, ‘e’, ‘i’, ‘u’]


Built-in Functions

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:

L1 = [‘a’, ‘p’, ‘p’, ‘l’, ‘e’]

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 = [‘f’, ‘a’, ‘y’, ‘z’]

L2.sort()

print (L2)

>>> [‘a’, ’f’, ‘y’, ‘z’]

To sort the list in descending order we can use –

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]

If you want the list to be sorted in descending order we can use –

sorted (list_name, reverse = True)

7. sum()

It returns the sum() of numbers in the list.

Ex:

L1 = [1,2,3]

print (sum(L1))

>>> 6

8. max()

This function returns the maximum elements in a list.

Ex:

L = [1,2,3]

print (max(L))

>>> 3

9. min()

This function returns the maximum elements in a list.

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

Definition and properties

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

print (type (T1))

>>> tuple

T1 = (7) #One Element

print (type (T1))

>>> int

T1 = (7,)

print (type (T1))

>>> 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

T1 = (‘a’, 10, 7.9, “apple”)

print (T1[ :3:2 ])

>>> (‘a’, 7.9)

print (T1[ 2: ])

>>> (7.9, “apple”)

print (T1[ : :-1 ])

>>> (“apple”, 7.9, ‘a’)

Tuple Operator

1. Tuple Concatenation ‘+’

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

print (4 not in T1)

>>> True

4. Comparison

Ex:

T1 = (1,2,3)

T2 = (4,5,6)

print ( T1 > T2)

>>> False

print ( T1 == T2)

>>> False

print ( T1 < T2)

>>> True

5. Packing and Unpacking Tuple

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

T1 = 1,2,3, [4,5,6], (7,8)

print (type(T1))

>>> class: tuple


#Uncpacking

T2 = (‘b’, ‘l’, ‘u’, ‘e’)

a1, a2, a3, a4 = T1

#Modifying an element in a tuple using list()

T1 = (1,2,3)

L1 = list(T1)

L1 [1] = ‘cat’

T1 = tuple(L1)

print (T1)

>>> (1, ‘cat’, 3)

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)

Traceback (most recent call last):

File "<pyshell#12>", line 1, in <module>

t2

NameError: name 't2' is not defined.

#delete individual elements of a tuple

T1 = (1,2,3)

L1 = list(T1)

del (L1[0])

print (T1)
>>> (2,3)_

#Unpacking & Packing

a, b = T1

T1 = b

print (T1)

>>> (3,)

Built-in Functions

1. id (tuple)

It returns the unique id for the specified tuple object.

2. len ()

This function returns length of the tuple.

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.

6. sorted (tuple, reverse = value)

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)

returns the count of an element or an object in a given sequence.

You might also like