0% found this document useful (0 votes)
5 views

Asm 114478

Uploaded by

Gaurav Gupta
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)
5 views

Asm 114478

Uploaded by

Gaurav Gupta
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/ 14

PYTHON NOTES (II)

LISTS IN PYTHON
 List is a sequence of values of any type.
 Values in the list are called elements / items.
 List is enclosed in square brackets.
 Example:
a = [1,2.3,"Hello"]
 List is one of the most frequently used and very versatile data type used in Python.

How to create a list ?


In Python programming, a list is created by placing all the items (elements) inside a square bracket [ ], separated
by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).
Example:
#empty list
empty_list = []
#list of integers
age = [15,12,18]
#list with mixed data types
student_height_weight = ["Ansh", 5.7, 60]
Note: A list can also have another list as an item. This is called nested lists.
# nested list
student marks = ["Aditya", "10-A", [ "english",75]]

How to access elements of a list ?


A list is made up of various elements which need to be individually accessed on the basis of the application it is
used for. There are two ways to access an individual element of a list:
1) List Index
2) Negative Indexing

©Lotus Valley Int. School, Gurugram


~1~
List Index
A list index is the position at which any element is present in the list. Index in the list starts from 0, so if a list has
5 elements the index will start from 0 and go on till 4. In order to access an element in a list we need to use index
operator [].
Negative Indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last
item and so on.

In order to access elements using negative indexing, we can use the negative index as mentioned in the above
figure.

©Lotus Valley Int. School, Gurugram


~2~
Adding Element to a List
We can add an element to any list using following methods :
1) Using append() method
2) Using insert() method
3) Using extend() method

©Lotus Valley Int. School, Gurugram


~3~
Using append( ) Method
Elements can be added to the List by using built-in append() function.
Only one element at a time can be added to the list by using append() method, for addition of multiple elements
with the append() method, loops are used.
Using insert() Method
append() method only works for addition of elements at the end of the List, for addition of element at the desired
position, insert() method is used. Unlike append() which takes only one argument, insert() method requires two
arguments(position, value).
Using extend() method
Other than append() and insert() methods, there's one more method for Addition of elements, extend(), this method
is used to add multiple elements at the same time at the end of the list.

Removing Elements from a List


Elements from a list can removed using two methods :
1) Using remove() method
2) Using pop() method

Elements can be removed from the List by using built-in remove() function but an Error arises if element doesn't
exist in the set. Remove() method only removes one element at a time, to remove range of elements, iterator is
used. The remove() method removes the specified item.

©Lotus Valley Int. School, Gurugram


~4~
Note – Remove method in List will only remove the first occurrence of the searched element.
Using pop() method
Pop() function can also be used to remove and return an element from the set, but by default it removes only the
last element of the set, to remove an element from a specific position of the List, index of the element is passed
as an argument to the pop() method.

Slicing of a List
In Python List, there are multiple ways to print the whole List with all the elements, but to print a specific range
of elements from the list, we use Slice operation.
Slice operation is performed on Lists with the use of colon(:).
To print elements from beginning to a range use [:Index], to print elements from end use [:-Index], to print
elements from specific Index till the end use [Index:], to print elements within a range, use [Start Index: End
Index] and to print whole List with the use of slicing operation, use [:]. Further, to print whole List in reverse
order, use [::-1].
Note – To print elements of List from rear end, use Negative Indexes.

©Lotus Valley Int. School, Gurugram


~5~
List Methods
Some of the other functions which can be used with lists are mentioned below:

©Lotus Valley Int. School, Gurugram


~6~
TUPLES IN PYTHON
 Tuple is a collection of Python objects which is ordered and unchangeable.
 The sequence of values stored in a tuple can be of any type, and they are indexed by integers.
 Values of a tuple are syntactically separated by ‘commas’.
 It is more common to define a tuple by closing the sequence of values in parentheses.
 Example:
fruits = ("apple", "banana", "cherry")

How to Create a tuple ?


In Python, tuples are created by placing sequence of values separated by ‘comma’ with or without the use of
parentheses for grouping of data sequence. It can contain any number of elements and of any datatype (like strings,
integers, list, etc.).
Example
#Creating an empty Tuple
Tuple1 = ()
#Creating a Tuple with the use of string
Tuple1 = ('Artificial', 'Intelligence')
#Creating a Tuple with Mixed Datatype
Tuple1 = (5, 'Artificial', 7, 'Intelligence')

Accessing of Tuples
We can use the index operator [] to access an item in a tuple where the index starts from 0.
So, a tuple having 6 elements will have indices from 0 to 5.
Trying to access an element outside of tuple (for example, 6, 7,...) will raise an IndexError.
The index must be an integer; so, we cannot use float or other types. This will result in TypeError.
Example
fruits = ("apple", "banana", "cherry")
print(fruits[1])
The above code will give the output as "banana"

Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. Entire tuple gets deleted by the use of
del() method.

©Lotus Valley Int. School, Gurugram


~7~
Example
num = (0, 1, 2, 3, 4)
del num

FLOW OF CONTROL AND CONDITIONS


In the programs we have seen till now, there has always been a series of statements faithfully executed by Python
in exact top-down order. What if you wanted to change the flow of how it works?
For example, you want the program to take some decisions and do different things depending on different
situations, such as printing 'Good Morning' or 'Good Evening' depending on the time of the day? As you might
have guessed, this is achieved using control flow statements.
There are three control flow statements in Python - if, for and while.

Decision Making Statements


On the occasion of World Health Day, one of the schools in the city decided to take an initiative to help students
maintain their health and be fit. Let’s observe an interesting conversation happening between the students when
they come to know about the initiative.

©Lotus Valley Int. School, Gurugram


~8~
There come situations in real life when we need to make some decisions and based on these decisions, we need
to decide what should we do next. Similar situations arise in programming also where we need to make some
decisions and based on these decisions we will execute the next block of code.
Decision making statements in programming languages decide the direction of flow of program execution.
Decision making statements available in Python are: ● if statement ● if..else statements ● if-elif ladder

If Statement

The if statement is used to check a condition: if the condition is true, we run a block of statements (called the if-
block).
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.
Note:
1) 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.
2) Python interprets non-zero values as True. None and 0 are interpreted as False.

Example :
#Check if the number is positive, we print an appropriate message
num = 3
if num > 0:
print(num, “is a positive number.”)
print(“this is always printed”)
num = -1
if num > 0:
print(num, “is a positive number.”)
print(“this is always printed”)

When you run the program, the output will be:


3 is a positive number

©Lotus Valley Int. School, Gurugram


~9~
This is always printed
This is also always printed.
In the above example, num > 0 is the test expression. The body of if is executed only if this evaluates to True.
When variable num is equal to 3, test expression is true and body inside body of if is executed.
If variable num is equal to -1, test expression is false and body inside body of if is skipped.
The print() statement falls outside of the if block (unindented). Hence, it is executed regardless of the test
expression.

Python if...else Statement

Syntax of if...else
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.
Example of if...else
#A program to check if a person can vote
age = input(“Enter Your Age”)
if age >= 18:
print(“You are eligible to vote”)
else:
print(“You are not eligible to vote”)

In the above example, when if the age entered by the person is greater than or equal to 18, he/she can vote.
Otherwise, the person is not eligible to vote

Python if...elif...else Statement

Syntax of if...elif...else
if test expression:
Body of if
©Lotus Valley Int. School, Gurugram
~ 10 ~
elif test expression:
Body of elif
else:
Body of else

The elif is short for else if. 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. 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.
Example of if...elif...else
#To check the grade of a student
Marks = 60
if marks > 75:
print("You get an A grade")
elif marks > 60:
print("You get a B grade")
else:
print("You get a C grade")

Python Nested if statements

We can have an 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. This can get confusing, so must be avoided if it can be.
Python Nested if Example
# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message

©Lotus Valley Int. School, Gurugram


~ 11 ~
# This time we use nested if
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

When you run the above program


Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero

Iteration Statements
The For Loop

The for..in statement is another looping statement which iterates over a sequence of objects i.e. go through each
item in a sequence.
Syntax of for Loop-
for val in sequence:
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each iteration.

©Lotus Valley Int. School, Gurugram


~ 12 ~
Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the
code using indentation.
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)

The while Statement

The while statement allows you to repeatedly execute a block of statements as long as a condition is true.
A while statement is an example of what is called a looping statement. A while statement can have an optional
else clause.
Syntax of while Loop in Python
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates
to True. After one iteration, the test expression is checked again. This process continues until the test_expression
evaluates to False. In Python, the body of the while loop is determined through indentation. Body starts with
indentation and the first unindented line marks the end. Python interprets any non-zero value as True. None and
0 are interpreted as False.
Example:
# Program to add natural
# numbers upto
# sum = 1+2+3+...+n
# To take input from the user,

©Lotus Valley Int. School, Gurugram


~ 13 ~
# n = int(input("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)

When you run the program, the output will be:


Enter n: 10
The sum is 55
In the above program, the test expression will be True as long as our counter variable i is less than or equal to n
(10 in our program).
We need to increase the value of the counter variable in the body of the loop. This is very important (and mostly
forgotten). Failing to do so will result in an infinite loop (never ending loop).
Finally, the result is displayed.

©Lotus Valley Int. School, Gurugram


~ 14 ~

You might also like