Notes On Loops and Lists
Notes On Loops and Lists
Notes On Loops and Lists
LOOPS:
Loops allow us to repeat certain parts of the code multiple times until the given condition is
satisfied, without having to rewrite that piece of code.
Explain FOR LOOP
The for statement allows you to specify how many times a statement or compound statement
should be repeated. A for statement’s body is executed one or more times until an optional
condition is met.
range() is a very useful function that returns a series of numbers in iterable form. Thus, it can be
used in for loop.
Syntax:
for val in sequence:
Body of for Example:
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
# Output: The sum is 48
print("The sum is", sum)
Output:
The sum is 48
2. Write a python program to find the largest number among the three input numbers.
Ans)
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)
NESTED LISTS
A list can be an element of another list
L1=[200,300,[600,700]]
There are three elements in the above list L1
L1[0] is 200
L1[1] is 300
L[2] is [600,700]
CHECKING THE LENGTH OF A LIST.
The length or size of a list means the number of elements of a list.
To check the number of elements of a list len() is used
Example
>>> list1=[1,2,3,4,10]
>>>len(list1)
5
type()
The type() will display the type of list when used with a listname .
>>>list2=[‘a’,’b’,’c’]
>>>type(list2)
<class ‘list’>
Indexing and accessing the elements of a list
POSITIVE INDEXING
Python lists items are numbered as 0,1,2,3 …….This is positive indexing.
The first element is having index number 0
The second element has index number 1
The last element has an index number length-1.
That means if there are 5 items in a list the last elements index number will be 4
NEGATIVE INDEXING
Python elements have negative indexing along with positive indexing
The last element’s negative index number will be -1
The second last element’s negative index number will be -2
The first element’s index number will be equal to the -(length) of the list.
For example, if there are 5 elements in a list the negative index of the first element will be -5
List elements can be accessed by the following statements
Listname[index number]
Example
>>>Mylist1=[100,200,300,400]
>>>mylist1[0]
100
The first element will be displayed. (This is Positive indexing )
>>>mylist1[-1]
400
Here negative indexing is used. The last element will be displayed.