Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Python statement

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Python statement

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

Ch-3

Python If-else statements


Decision making is the most important aspect of almost all the programming languages.
As the name implies, decision making allows us to run a particular block of code for a
particular decision. Here, the decisions are made on the validity of the particular
conditions. Condition checking is the backbone of decision making.

In python, decision making is performed by the following statements.

Statement Description

If Statement The if statement is used to test a specific condition. If the condition is true, a block o
be executed.

If - else The if-else statement is similar to if statement except the fact that, it also provides th
Statement for the false case of the condition to be checked. If the condition provided in the i
then the else statement will be executed.

Nested if Nested if statements enable us to use if ? else statement inside an outer if statement.
Statement

Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If
two statements are at the same indentation level, then they are the part of the same
block.

Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.

Indentation is the most used part of the python language since it declares the block of
code. All the statements of one block are intended at the same level indentation. We will
see how the actual indentation takes place in decision making and other stuff in python.

The if statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be any
valid logical expression which can be either evaluated to true or false.

The syntax of the if-statement is given below.

1. if expression:
2. statement

Example 1

1. # Simple Python program to understand the if statement


2. num = int(input("enter the number:"))
3. # Here, we are taking an integer num and taking input dynamically
4. if num%2 == 0:
5. # Here, we are checking the condition. If the condition is true, we will enter the block
6. print("The Given number is an even number")

Output:

enter the number: 10


The Given number is an even number

Example 2 : Program to print the largest of the three numbers.

1. # Simple Python Program to print the largest of the three numbers.


2. a = int (input("Enter a: "));
3. b = int (input("Enter b: "));
4. c = int (input("Enter c: "));
5. if a>b and a>c:
6. # Here, we are checking the condition. If the condition is true, we will enter the block
7. print ("From the above three numbers given a is largest");
8. if b>a and b>c:
9. # Here, we are checking the condition. If the condition is true, we will enter the block
10. print ("From the above three numbers given b is largest");
11. if c>a and c>b:
12. # Here, we are checking the condition. If the condition is true, we will enter the block
13. print ("From the above three numbers given c is largest");

Output:

Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest

The if-else statement


The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.

ADVERTISEMENT
ADVERTISEMENT
If the condition is true, then the if-block is executed. Otherwise, the else-block is
executed.

The syntax of the if-else statement is given below.

1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
Example 1 : Program to check whether a person is eligible to vote
or not.

1. # Simple Python Program to check whether a person is eligible to vote or not.


2. age = int (input("Enter your age: "))
3. # Here, we are taking an integer num and taking input dynamically
4. if age>=18:
5. # Here, we are checking the condition. If the condition is true, we will enter the block
6. print("You are eligible to vote !!");
7. else:
8. print("Sorry! you have to wait !!");

Output:

Enter your age: 90


You are eligible to vote !!

Example 2: Program to check whether a number is even or not.

1. # Simple Python Program to check whether a number is even or not.


2. num = int(input("enter the number:"))
3. # Here, we are taking an integer num and taking input dynamically
4. if num%2 == 0:
5. # Here, we are checking the condition. If the condition is true, we will enter the block
6. print("The Given number is an even number")
7. else:
8. print("The Given Number is an odd number")

Output:

enter the number: 10


The Given number is even number

The elif statement


The elif statement enables us to check multiple conditions and execute the specific
block of statements depending upon the true condition among them. We can have any
number of elif statements in our program depending upon our need. However, using
elif is optional.
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by
an if statement.

The syntax of the elif statement is given below.

ADVERTISEMENT
ADVERTISEMENT

1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
11. # block of statements
Example 1

1. # Simple Python program to understand elif statement


2. number = int(input("Enter the number?"))
3. # Here, we are taking an integer number and taking input dynamically
4. if number==10:
5. # Here, we are checking the condition. If the condition is true, we will enter the block
6. print("The given number is equals to 10")
7. elif number==50:
8. # Here, we are checking the condition. If the condition is true, we will enter the block
9. print("The given number is equal to 50");
10. elif number==100:
11. # Here, we are checking the condition. If the condition is true, we will enter the block
12. print("The given number is equal to 100");
13. else:
14. print("The given number is not equal to 10, 50 or 100");

Output:

Enter the number?15


The given number is not equal to 10, 50 or 100

Example 2

1. # Simple Python program to understand elif statement


2. marks = int(input("Enter the marks? "))
3. # Here, we are taking an integer marks and taking input dynamically
4. if marks > 85 and marks <= 100:
5. # Here, we are checking the condition. If the condition is true, we will enter the block
6. print("Congrats ! you scored grade A ...")
7. elif marks > 60 and marks <= 85:
8. # Here, we are checking the condition. If the condition is true, we will enter the block
9. print("You scored grade B + ...")
10. elif marks > 40 and marks <= 60:
11. # Here, we are checking the condition. If the condition is true, we will enter the block
12. print("You scored grade B ...")
13. elif (marks > 30 and marks <= 40):
14. # Here, we are checking the condition. If the condition is true, we will enter the block
15. print("You scored grade C ...")
16. else:
17. print("Sorry you are fail ?")

Output:

Enter the marks? 89


Congrats ! you scored grade A ...

Python Loops
The following loops are available in Python to fulfil the looping needs. Python offers 3
choices for running the loops. The basic functionality of all the techniques is the same,
although the syntax and the amount of time required for checking the condition differ.

We can run a single statement or set of statements repeatedly using a loop command.

The following sorts of loops are available in the Python programming language.

Sr.No. Name of the Loop Type & Description


loop

1 While loop Repeats a statement or group of statements while a given condition is


condition before executing the loop body.

2 For loop This type of loop executes a code block multiple times and abbreviates the
the loop variable.

3 Nested loops We can iterate a loop inside another loop.

Loop Control Statements


Statements used to control loops and change the course of iteration are called control
statements. All the objects produced within the local scope of the loop are deleted
when execution is completed.

ADVERTISEMENT

ADVERTISEMENT

Python provides the following control statements. We will discuss them later in detail.

Let us quickly go over the definitions of these loop control statements.


Sr.No. Name of the Description
control statement

1 Break statement This command terminates the loop's execution and transfers the p
the statement next to the loop.

2 Continue statement This command skips the current iteration of the loop. The statem
continue statement are not executed once the Python interpreter re
statement.

3 Pass statement The pass statement is used when a statement is syntactically necessar
be executed.

The for Loop


Python's for loop is designed to repeatedly execute a code block while iterating through
a list, tuple, dictionary, or other iterable objects of Python. The process of traversing a
sequence is known as iteration.

Syntax of the for Loop

1. for value in sequence:


2. { code block }

In this case, the variable value is used to hold the value of every item present in the
sequence before the iteration begins until this particular iteration is completed.

Loop iterates until the final item of the sequence are reached.

ADVERTISEMENT
ADVERTISEMENT

Code

1. # Python program to show how the for loop works


2.
3. # Creating a sequence which is a tuple of numbers
4. numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
5.
6. # variable to store the square of the number
7. square = 0
8.
9. # Creating an empty list
10. squares = []
11.
12. # Creating a for loop
13. for value in numbers:
14. square = value ** 2
15. squares.append(square)
16. print("The list of squares is", squares)

Output:

The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]

Using else Statement with for Loop


As already said, a for loop executes the code block until the sequence element is
reached. The statement is written right after the for loop is executed after the execution
of the for loop is complete.

Only if the execution is complete does the else statement comes into play. It won't be
executed if we exit the loop or if an error is thrown.

Here is a code to better understand if-else statements.

Code

1. # Python program to show how if-else statements work


2.
3. string = "Python Loop"
4.
5. # Initiating a loop
6. for s in a string:
7. # giving a condition in if block
8. if s == "o":
9. print("If block")
10. # if condition is not satisfied then else block will be executed
11. else:
12. print(s)

Output:

ADVERTISEMENT
ADVERTISEMENT

P
y
t
h
If block
n

L
If block
If block
p

Now similarly, using else with for loop.

Syntax:

1. for value in sequence:


2. # executes the statements until sequences are exhausted
3. else:
4. # executes these statements when for loop is completed

Code

ADVERTISEMENT

1. # Python program to show how to use else statement with for loop
2.
3. # Creating a sequence
4. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
5.
6. # Initiating the loop
7. for value in tuple_:
8. if value % 2 != 0:
9. print(value)
10. # giving an else statement
11. else:
12. print("These are the odd numbers present in the tuple")

Output:

3
9
3
9
7
These are the odd numbers present in the tuple

The range() Function


With the help of the range() function, we may produce a series of numbers. range(10)
will produce values between 0 and 9. (10 numbers).

ADVERTISEMENT
ADVERTISEMENT

We can give specific start, stop, and step size values in the manner range(start, stop,
step size). If the step size is not specified, it defaults to 1.

Since it doesn't create every value it "contains" after we construct it, the range object
can be characterized as being "slow." It does provide in, len, and __getitem__ actions,
but it is not an iterator.

The example that follows will make this clear.

Code

1. # Python program to show the working of range() function


2.
3. print(range(15))
4.
5. print(list(range(15)))
6.
7. print(list(range(4, 9)))
8.
9. print(list(range(5, 25, 4)))

Output:
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]

To iterate through a sequence of items, we can apply the range() method in for loops.
We can use indexing to iterate through the given sequence by combining it with an
iterable's len() function. Here's an illustration.

ADVERTISEMENT
ADVERTISEMENT

Code

1. # Python program to iterate over a sequence with the help of indexing


2.
3. tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")
4.
5. # iterating over tuple_ using range() function
6. for iterator in range(len(tuple_)):
7. print(tuple_[iterator].upper())

Output:

PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE

While Loop
While loops are used in Python to iterate until a specified condition is met. However, the
statement in the program that follows the while loop is executed once the condition
changes to false.

Syntax of the while loop is:

1. while <condition>:
2. { code block }

All the coding statements that follow a structural command define a code block. These
statements are intended with the same number of spaces. Python groups statements
together with indentation.
Code

1. # Python program to show how to use a while loop


2. counter = 0
3. # Initiating the loop
4. while counter < 10: # giving the condition
5. counter = counter + 3
6. print("Python Loops")

Output:

Python Loops
Python Loops
Python Loops
Python Loops

Using else Statement with while Loops


As discussed earlier in the for loop section, we can use the else statement with the while
loop also. It has the same syntax.

ADVERTISEMENT
ADVERTISEMENT

Code

1. #Python program to show how to use else statement with the while loop
2. counter = 0
3.
4. # Iterating through the while loop
5. while (counter < 10):
6. counter = counter + 3
7. print("Python Loops") # Executed untile condition is met
8. # Once the condition of while loop gives False this statement will be executed
9. else:
10. print("Code block inside the else statement")

Output:

Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement

Single statement while Block


The loop can be declared in a single statement, as seen below. This is similar to the if-
else block, where we can write the code block in a single line.

Code

1. # Python program to show how to write a single statement while loop


2. counter = 0
3. while (count < 3): print("Python Loops")

Loop Control Statements


Now we will discuss the loop control statements in detail. We will see an example of
each control statement.

Continue Statement
It returns the control to the beginning of the loop.

ADVERTISEMENT
ADVERTISEMENT

Code

1. # Python program to show how the continue statement works


2.
3. # Initiating the loop
4. for string in "Python Loops":
5. if string == "o" or string == "p" or string == "t":
6. continue
7. print('Current Letter:', string)

Output:

Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s

Break Statement
It stops the execution of the loop when the break statement is reached.

Code

1. # Python program to show how the break statement works


2.
3. # Initiating the loop
4. for string in "Python Loops":
5. if string == 'L':
6. break
7. print('Current Letter: ', string)

Output:

Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:

Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for
classes, functions, and empty control statements.

Code

1. # Python program to show how the pass statement works


2. for a string in "Python Loops":
3. pass
4. print( 'Last Letter:', string)

Output:
Last Letter: s

Python for loop


Python is a strong, universally applicable prearranging language planned to be easy to
comprehend and carry out. It is allowed to get to because it is open-source. In this
tutorial, we will learn how to use Python for loops, one of the most fundamental looping
instructions in Python programming.

Introduction to for Loop in Python


Python frequently uses the Loop to iterate over iterable objects like lists, tuples, and
strings. Crossing is the most common way of emphasizing across a series, for loops are
used when a section of code needs to be repeated a certain number of times. The for-
circle is typically utilized on an iterable item, for example, a rundown or the in-fabricated
range capability. In Python, the for Statement runs the code block each time it traverses
a series of elements. On the other hand, the "while" Loop is used when a condition
needs to be verified after each repetition or when a piece of code needs to be repeated
indefinitely. The for Statement is opposed to this Loop.

Syntax of for Loop

1. for value in sequence:


2. {loop body}

The value is the parameter that determines the element's value within the iterable
sequence on each iteration. When a sequence contains expression statements, they are
processed first. The first element in the sequence is then assigned to the iterating
variable iterating_variable. From that point onward, the planned block is run. Each
element in the sequence is assigned to iterating_variable during the statement block
until the sequence as a whole is completed. Using indentation, the contents of the Loop
are distinguished from the remainder of the program.

Example of Python for Loop


Code

1. # Code to find the sum of squares of each element of the list using for loop
2.
3. # creating the list of numbers
4. numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
5.
6. # initializing a variable that will store the sum
7. sum_ = 0
8.
9. # using for loop to iterate over the list
10. for num in numbers:
11.
12. sum_ = sum_ + num ** 2
13.
14. print("The sum of squares is: ", sum_)

Output:

The sum of squares is: 774

The range() Function


Since the "range" capability shows up so habitually in for circles, we could erroneously
accept the reach as a part of the punctuation of for circle. It's not: It is a built-in Python
method that fulfills the requirement of providing a series for the for expression to run
over by following a particular pattern (typically serial integers). Mainly, they can act
straight on sequences, so counting is unnecessary. This is a typical novice construct if
they originate from a language with distinct loop syntax:

Code

1. my_list = [3, 5, 6, 8, 4]
2. for iter_var in range( len( my_list ) ):
3. my_list.append(my_list[iter_var] + 2)
4. print( my_list )

Output:

[3, 5, 6, 8, 4, 5, 7, 8, 10, 6]

Iterating by Using Index of Sequence


Another method of iterating through every item is to use an index offset within the
sequence. Here's a simple illustration:

Code

1. # Code to find the sum of squares of each element of the list using for loop
2.
3. # creating the list of numbers
4. numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
5.
6. # initializing a variable that will store the sum
7. sum_ = 0
8.
9. # using for loop to iterate over list
10. for num in range( len(numbers) ):
11.
12. sum_ = sum_ + numbers[num] ** 2
13.
14. print("The sum of squares is: ", sum_)

Output:

The sum of squares is: 774

The len() worked in a technique that profits the complete number of things in the
rundown or tuple, and the implicit capability range(), which returns the specific grouping
to emphasize over, proved helpful here.

Using else Statement with for Loop


A loop expression and an else expression can be connected in Python.

After the circuit has finished iterating over the list, the else clause is combined with a for
Loop.

The following example demonstrates how to extract students' marks from the record by
combining a for expression with an otherwise statement.

Code
1. # code to print marks of a student from the record
2. student_name_1 = 'Itika'
3. student_name_2 = 'Parker'
4.
5.
6. # Creating a dictionary of records of the students
7. records = {'Itika': 90, 'Arshia': 92, 'Peter': 46}
8. def marks( student_name ):
9. for a_student in record: # for loop will iterate over the keys of the dictionary
10. if a_student == student_name:
11. return records[ a_student ]
12. break
13. else:
14. return f'There is no student of name {student_name} in the records'
15.
16. # giving the function marks() name of two students
17. print( f"Marks of {student_name_1} are: ", marks( student_name_1 ) )
18. print( f"Marks of {student_name_2} are: ", marks( student_name_2 ) )

Output:

Marks of Itika are: 90


Marks of Parker are: There is no student of name Parker in the records

Nested Loops
If we have a piece of content that we need to run various times and, afterward, one
more piece of content inside that script that we need to run B several times, we utilize a
"settled circle." While working with an iterable in the rundowns, Python broadly uses
these.

Code

1. import random
2. numbers = [ ]
3. for val in range(0, 11):
4. numbers.append( random.randint( 0, 11 ) )
5. for num in range( 0, 11 ):
6. for i in numbers:
7. if num == i:
8. print( num, end = " " )

Output:

0 2 4 5 6 7 8 8 9 10

Python While Loops


In coding, loops are designed to execute a specified code block repeatedly. We'll learn
how to construct a while loop in Python, the syntax of a while loop, loop controls like
break and continue, and other exercises in this tutorial.

Introduction of Python While Loop


In this article, we are discussing while loops in Python. The Python while loop iteration of
a code block is executed as long as the given Condition, i.e., conditional_expression, is
true.

If we don't know how many times we'll execute the iteration ahead of time, we can write
an indefinite loop.

Syntax of Python While Loop

ADVERTISEMENT

ADVERTISEMENT

Now, here we discuss the syntax of the Python while loop. The syntax is given below -

1. Statement
2. while Condition:
3. Statement

The given condition, i.e., conditional_expression, is evaluated initially in the Python while
loop. Then, if the conditional expression gives a boolean value True, the while loop
statements are executed. The conditional expression is verified again when the complete
code block is executed. This procedure repeatedly occurs until the conditional
expression returns the boolean value False.

ADVERTISEMENT

o The statements of the Python while loop are dictated by indentation.


o The code block begins when a statement is indented & ends with the very first
unindented statement.
o Any non-zero number in Python is interpreted as boolean True. False is
interpreted as None and 0.

Example
Now we give some examples of while Loop in Python. The examples are given in below -

Program code 1:

Now we give code examples of while loops in Python for printing numbers from 1 to 10.
The code is given below -

1. i=1
2. while i<=10:
3. print(i, end=' ')
4. i+=1

Output:

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -

1 2 3 4 5 6 7 8 9 10

Program Code 2:

Now we give code examples of while loops in Python for Printing those numbers
divisible by either 5 or 7 within 1 to 50 using a while loop. The code is given below -

1. i=1
2. while i<51:
3. if i%5 == 0 or i%7==0 :
4. print(i, end=' ')
5. i+=1

Output:

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -

5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50

Program Code:

Now we give code examples of while loops in Python, the sum of squares of the first 15
natural numbers using a while loop. The code is given below -

1. # Python program example to show the use of while loop


2.
3. num = 15
4.
5. # initializing summation and a counter for iteration
6. summation = 0
7. c = 1
8.
9. while c <= num: # specifying the condition of the loop
10. # begining the code block
11. summation = c**2 + summation
12. c=c+1 # incrementing the counter
13.
14. # print the final sum
15. print("The sum of squares is", summation)

Output:

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -

The sum of squares is 1240


Provided that our counter parameter i gives boolean true for the condition, i less than or
equal to num, the loop repeatedly executes the code block i number of times.

ADVERTISEMENT
ADVERTISEMENT

Next is a crucial point (which is mostly forgotten). We have to increment the counter
parameter's value in the loop's statements. If we don't, our while loop will execute itself
indefinitely (a never-ending loop).

Finally, we print the result using the print statement.

Exercises of Python While Loop


Prime Numbers and Python While Loop
Using a while loop, we will construct a Python program to verify if the given integer is a
prime number or not.

Program Code:

Now we give code examples of while loops in Python for a number is Prime number or
not. The code is given below -

1. num = [34, 12, 54, 23, 75, 34, 11]


2.
3. def prime_number(number):
4. condition = 0
5. iteration = 2
6. while iteration <= number / 2:
7. if number % iteration == 0:
8. condition = 1
9. break
10. iteration = iteration + 1
11.
12. if condition == 0:
13. print(f"{number} is a PRIME number")
14. else:
15. print(f"{number} is not a PRIME number")
16. for i in num:
17. prime_number(i)

Output:

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -

34 is not a PRIME number


12 is not a PRIME number
54 is not a PRIME number
23 is a PRIME number
75 is not a PRIME number
34 is not a PRIME number
11 is a PRIME number

2. Armstrong and Python While Loop


We will construct a Python program using a while loop to verify whether the given
integer is an Armstrong number.

ADVERTISEMENT

Program Code:

Now we give code examples of while loops in Python for a number is Armstrong
number or not. The code is given below -

1. n = int(input())
2. n1=str(n)
3. l=len(n1)
4. temp=n
5. s=0
6. while n!=0:
7. r=n%10
8. s=s+(r**1)
9. n=n//10
10. if s==temp:
11. print("It is an Armstrong number")
12. else:
13. print("It is not an Armstrong number ")
Output:

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -

342
It is not an Armstrong number

Multiplication Table using While Loop


In this example, we will use the while loop for printing the multiplication table of a given
number.

Program Code:

In this example, we will use the while loop for printing the multiplication table of a given
number. The code is given below -

ADVERTISEMENT

1. num = 21
2. counter = 1
3. # we will use a while loop for iterating 10 times for the multiplication table
4. print("The Multiplication Table of: ", num)
5. while counter <= 10: # specifying the condition
6. ans = num * counter
7. print (num, 'x', counter, '=', ans)
8. counter += 1 # expression to increment the counter

Output:

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -

The Multiplication Table of: 21


21 x 1 = 21
21 x 2 = 42
21 x 3 = 63
21 x 4 = 84
21 x 5 = 105
21 x 6 = 126
21 x 7 = 147
21 x 8 = 168
21 x 9 = 189
21 x 10 = 210

Python While Loop with List


Program Code 1:

Now we give code examples of while loops in Python for square every number of a list.
The code is given below -

1. # Python program to square every number of a list


2. # initializing a list
3. list_ = [3, 5, 1, 4, 6]
4. squares = []
5. # programing a while loop
6. while list_: # until list is not empty this expression will give boolean True after that False

7. squares.append( (list_.pop())**2)
8. # Print the squares of all numbers.
9. print( squares )

Output:

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -

ADVERTISEMENT

[36, 16, 1, 25, 9]

In the preceding example, we execute a while loop over a given list of integers that will
repeatedly run if an element in the list is found.

Program Code 2:

Now we give code examples of while loops in Python for determine odd and even
number from every number of a list. The code is given below -

1. list_ = [3, 4, 8, 10, 34, 45, 67,80] # Initialize the list


2. index = 0
3. while index < len(list_):
4. element = list_[index]
5. if element % 2 == 0:
6. print('It is an even number') # Print if the number is even.
7. else:
8. print('It is an odd number') # Print if the number is odd.
9. index += 1

Output:

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -

It is an odd number
It is an even number
It is an even number
It is an even number
It is an even number
It is an odd number
It is an odd number
It is an even number

Program Code 3:

Now we give code examples of while loops in Python for determine the number letters
of every word from the given list. The code is given below -

1. List_= ['Priya', 'Neha', 'Cow', 'To']


2. index = 0
3. while index < len(List_):
4. element = List_[index]
5. print(len(element))
6. index += 1

Output:

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -

5
4
3
2
Python While Loop Multiple Conditions
We must recruit logical operators to combine two or more expressions specifying
conditions into a single while loop. This instructs Python on collectively analyzing all the
given expressions of conditions.

We can construct a while loop with multiple conditions in this example. We have given
two conditions and a and keyword, meaning the Loop will execute the statements until
both conditions give Boolean True.

Program Code:

Now we give code examples of while loops in Python for multiple condition. The code is
given below -

1. num1 = 17
2. num2 = -12
3.
4. while num1 > 5 and num2 < -5 : # multiple conditions in a single while loop
5. num1 -= 2
6. num2 += 3
7. print( (num1, num2) )

Output:

ADVERTISEMENT

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -

(15, -9)
(13, -6)
(11, -3)

Let's look at another example of multiple conditions with an OR operator.

Code

1. num1 = 17
2. num2 = -12
3.
4. while num1 > 5 or num2 < -5 :
5. num1 -= 2
6. num2 += 3
7. print( (num1, num2) )

Output:

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -

(15, -9)
(13, -6)
(11, -3)
(9, 0)
(7, 3)
(5, 6)

We can also group multiple logical expressions in the while loop, as shown in this
example.

Code

1. num1 = 9
2. num = 14
3. maximum_value = 4
4. counter = 0
5. while (counter < num1 or counter < num2) and not counter >= maximum_value: # grou
ping multiple conditions
6. print(f"Number of iterations: {counter}")
7. counter += 1

Output:

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -

Number of iterations: 0
Number of iterations: 1
Number of iterations: 2
Number of iterations: 3

Single Statement While Loop


Similar to the if statement syntax, if our while clause consists of one statement, it may be
written on the same line as the while keyword.

Here is the syntax and example of a one-line while clause -

1. # Python program to show how to create a single statement while loop


2. counter = 1
3. while counter: print('Python While Loops')

Loop Control Statements


Now we will discuss the loop control statements in detail. We will see an example of
each control statement.

Continue Statement
It returns the control of the Python interpreter to the beginning of the loop.

Code

1. # Python program to show how to use continue loop control


2.
3. # Initiating the loop
4. for string in "While Loops":
5. if string == "o" or string == "i" or string == "e":
6. continue
7. print('Current Letter:', string)

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -

Output:

Current Letter: W
Current Letter: h
Current Letter: l
Current Letter:
Current Letter: L
Current Letter: p
Current Letter: s
Break Statement
It stops the execution of the loop when the break statement is reached.

ADVERTISEMENT

Code

1. # Python program to show how to use the break statement


2.
3. # Initiating the loop
4. for string in "Python Loops":
5. if string == 'n':
6. break
7. print('Current Letter: ', string)

Output:

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -

Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o

Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for
classes, functions, and empty control statements.

Code

1. # Python program to show how to use the pass statement


2. for a string in "Python Loops":
3. pass
4. print( 'The Last Letter of given string is:', string)

Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
Output:

The Last Letter of given string is: s

Python break statement


The break is a keyword in python which is used to bring the program control out of the
loop. The break statement breaks the loops one by one, i.e., in the case of nested loops,
it breaks the inner loop first and then proceeds to outer loops. In other words, we can
say that break is used to abort the current execution of the program and the control
goes to the next line after the loop.

The break is commonly used in the cases where we need to break the loop for a given
condition. The syntax of the break statement in Python is given below.

Syntax:

1. #loop statements
2. break;

Example 1 : break statement with for loop


Code

1. # break statement example


2. my_list = [1, 2, 3, 4]
3. count = 1
4. for item in my_list:
5. if item == 4:
6. print("Item matched")
7. count += 1
8. break
9. print("Found at location", count)

Output:

Item matched
Found at location 2

In the above example, a list is iterated using a for loop. When the item is matched with
value 4, the break statement is executed, and the loop terminates. Then the count is
printed by locating the item.

Example 2 : Breaking out of a loop early


Code

1. # break statement example


2. my_str = "python"
3. for char in my_str:
4. if char == 'o':
5. break
6. print(char)

Output:

p
y
t
h

When the character is found in the list of characters, break starts executing, and iterating
stops immediately. Then the next line of the print statement is printed.

Example 3: break statement with while loop


Code
1. # break statement example
2. i = 0;
3. while 1:
4. print(i," ",end=""),
5. i=i+1;
6. if i == 10:
7. break;
8. print("came out of while loop");

Output:

0 1 2 3 4 5 6 7 8 9 came out of while loop

It is the same as the above programs. The while loop is initialised to True, which is an
infinite loop. When the value is 10 and the condition becomes true, the break statement
will be executed and jump to the later print statement by terminating the while loop.

Example 4 : break statement with nested loops


Code

1. # break statement example


2. n = 2
3. while True:
4. i=1
5. while i <= 10:
6. print("%d X %d = %d\n" % (n, i, n * i))
7. i += 1
8. choice = int(input("Do you want to continue printing the table? Press 0 for no: "))
9. if choice == 0:
10. print("Exiting the program...")
11. break
12. n += 1
13. print("Program finished successfully.")

Output:

2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
Do you want to continue printing the table? Press 0 for no: 1
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
Do you want to continue printing the table? Press 0 for no: 0
Exiting the program...
Program finished successfully.

There are two nested loops in the above program. Inner loop and outer loop The inner
loop is responsible for printing the multiplication table, whereas the outer loop is
responsible for incrementing the n value. When the inner loop completes execution, the
user will have to continue printing. When 0 is entered, the break statement finally
executes, and the nested loop is terminated.

Python continue Statement


Python continue keyword is used to skip the remaining statements of the current loop
and go to the next iteration. In Python, loops repeat processes on their own in an
efficient way. However, there might be occasions when we wish to leave the current
loop entirely, skip iteration, or dismiss the condition controlling the loop.

We use Loop control statements in such cases. The continue keyword is a loop control
statement that allows us to change the loop's control. Both Python while and Python for
loops can leverage the continue statements.

Syntax:

1. continue

Python Continue Statements in for Loop


Printing numbers from 10 to 20 except 15 can be done using continue statement and
for loop. The following code is an example of the above scenario:

Code

1. # Python code to show example of continue statement


2.
3. # looping from 10 to 20
4. for iterator in range(10, 21):
5.
6. # If iterator is equals to 15, loop will continue to the next iteration
7. if iterator == 15:
8. continue
9. # otherwise printing the value of iterator
10. print( iterator )

Output:

10
11
12
13
14
16
17
18
19
20

Explanation: We will execute a loop from 10 to 20 and test the condition that the
iterator is equal to 15. If it equals 15, we'll employ the continue statement to skip to the
following iteration displaying any output; otherwise, the loop will print the result.

Python Continue Statements in while Loop


Code

1. # Creating a string
2. string = "JavaTpoint"
3. # initializing an iterator
4. iterator = 0
5.
6. # starting a while loop
7. while iterator < len(string):
8. # if loop is at letter a it will skip the remaining code and go to next iteration
9. if string[iterator] == 'a':
10. continue
11. # otherwise it will print the letter
12. print(string[ iterator ])
13. iterator += 1

Output:

J
v
T
p
o
i
n
t

Explanation: We will take a string "Javatpoint" and print each letter of the string except
"a". This time we will use Python while loop to do so. Until the value of the iterator is
less than the string's length, the while loop will keep executing.

Python Continue statement in list comprehension


Let's see the example for continue statement in list comprehension.

Code

1. numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


2.
3. # Using a list comprehension with continue
4. sq_num = [num ** 2 for num in numbers if num % 2 == 0]
5. # This will skip odd numbers and only square the even numbers
6. print(sq_num)

Output:

[4, 16, 36, 64, 100]


Explanation: In the above code, list comprehension will square the numbers from the
list. And continue statement will be encountered when odd numbers come and the loop
will skip the execution and moves to the next iterartion.

Python Continue vs. Pass


Usually, there is some confusion in the pass and continue keywords. So here are the
differences between these two.

Headings continue pass

Definition The continue statement is utilized to skip the current loop's The pass keyword is use
remaining statements, go to the following iteration, and necessary syntactically t
return control to the beginning. to be executed.

Action It takes the control back to the start of the loop. Nothing happens if the
encounters the pass stat

Application It works with both the Python while and Python for loops. It performs nothing; h
operation.

Syntax It has the following syntax: -: continue Its syntax is as follows:-

Interpretation It's mostly utilized within a loop's condition. During the byte-comp
keyword is removed.

Python Pass Statement


In this tutorial, we will learn more about past statements. It is interpreted as a
placeholder for future functions, classes, loops, and other operations.

What is Python's Pass Statement?


The pass statement is also known as the null statement. The Python mediator doesn't
overlook a Remark, though a pass proclamation isn't. As a result, these two Python
keywords are distinct.

We can use the pass statement as a placeholder when unsure of the code to provide.
Therefore, the pass only needs to be placed on that line. The pass might be utilized
when we wish no code to be executed. We can simply insert a pass in cases where
empty code is prohibited, such as in loops, functions, class definitions, and if-else
statements.

Syntax

1. Keyword:
2. pass

Ordinarily, we use it as a perspective for what's to come.

Let's say we have an if-else statement or loop that we want to fill in the future but
cannot. An empty body for the pass keyword would be grammatically incorrect. A
mistake would be shown by the Python translator proposing to occupy the space. As a
result, we use the pass statement to create a code block that does nothing.

An Illustration of the Pass Statement

Code

1. # Python program to show how to use a pass statement in a for loop


2. '''''pass acts as a placeholder. We can fill this place later on'''
3. sequence = {"Python", "Pass", "Statement", "Placeholder"}
4. for value in sequence:
5. if value == "Pass":
6. pass # leaving an empty if block using the pass keyword
7. else:
8. print("Not reached pass keyword: ", value)

Output:

Not reached pass keyword: Python


Not reached pass keyword: Placeholder
Not reached pass keyword: Statement

The same thing is also possible to create an empty function or a class.

Code

1. # Python program to show how to create an empty function and an empty class
2.
3. # Empty function:
4. def empty():
5. pass
6.
7. # Empty class
8. class Empty:
9. pass

Python String
Till now, we have discussed numbers as the standard data-types in Python. In this
section of the tutorial, we will discuss the most popular data type in Python, i.e., string.

Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes. The computer does not understand the characters; internally, it
stores manipulated character as the combination of the 0's and 1's.

Each character is encoded in the ASCII or Unicode character. So we can say that Python
strings are also called the collection of Unicode characters.

In Python, strings can be created by enclosing the character or the sequence of


characters in the quotes. Python allows us to use single quotes, double quotes, or triple
quotes to create the string.

Consider the following example in Python to create a string.

Syntax:

1. str = "Hi Python !"

Here, if we check the type of the variable str using a Python script

1. print(type(str)), then it will print a string (str).

In Python, strings are treated as the sequence of characters, which means that Python
doesn't support the character data-type; instead, a single character written as 'p' is
treated as the string of length 1.
Creating String in Python
We can create a string by enclosing the characters in single-quotes or double- quotes.
Python also provides triple-quotes to represent the string, but it is generally used for
multiline string or docstrings.

1. #Using single quotes


2. str1 = 'Hello Python'
3. print(str1)
4. #Using double quotes
5. str2 = "Hello Python"
6. print(str2)
7.
8. #Using triple quotes
9. str3 = '''''Triple quotes are generally used for
10. represent the multiline or
11. docstring'''
12. print(str3)

Output:

Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring

Strings indexing and splitting


Like other languages, the indexing of the Python strings starts from 0. For example, The
string "HELLO" is indexed as given in the below figure.

ADVERTISEMENT
Consider the following example:

1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])

Output:

H
E
L
L
O
IndexError: string index out of range
As shown in Python, the slice operator [] is used to access the individual characters of
the string. However, we can use the : (colon) operator in Python to access the substring
from the given string. Consider the following example.

Here, we must notice that the upper range given in the slice operator is always exclusive
i.e., if str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and
nothing else.

Consider the following example:

1. # Given String
2. str = "JAVATPOINT"
3. # Start Oth index to end
4. print(str[0:])
5. # Starts 1th index to 4th index
6. print(str[1:5])
7. # Starts 2nd index to 3rd index
8. print(str[2:4])
9. # Starts 0th to 2nd index
10. print(str[:3])
11. #Starts 4th to 6th index
12. print(str[4:7])

Output:

JAVATPOINT
AVAT
VA
JAV
TPO

We can do the negative slicing in the string; it starts from the rightmost character, which
is indicated as -1. The second rightmost index indicates -2, and so on. Consider the
following image.

Consider the following example

1. str = 'JAVATPOINT'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
7. # Reversing the given string
8. print(str[::-1])
9. print(str[-12])

Output:

T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range

Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string
object doesn't support item assignment i.e., A string can only be replaced with new
string since its content cannot be partially replaced. Strings are immutable in Python.

Consider the following example.

Example 1

1. str = "HELLO"
2. str[0] = "h"
3. print(str)

Output:

Traceback (most recent call last):


File "12.py", line 2, in <module>
str[0] = "h";
TypeError: 'str' object does not support item assignment

However, in example 1, the string str can be assigned completely to a new content as
specified in the following example.
Example 2

1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)

Output:

HELLO
hello

Deleting the String


As we know that strings are immutable. We cannot delete or remove the characters
from the string. But we can delete the entire string using the del keyword.

1. str = "JAVATPOINT"
2. del str[1]

Output:

TypeError: 'str' object doesn't support item deletion

Now we are deleting entire string.

1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)

Output:

NameError: name 'str1' is not defined

String Operators

Operator Description

+ It is known as concatenation operator used to join the strings given either side of the oper
* It is known as repetition operator. It concatenates the multiple copies of the same string.

[] It is known as slice operator. It is used to access the sub-strings of a particular string.

[:] It is known as range slice operator. It is used to access the characters from the specified ra

in It is known as membership operator. It returns if a particular sub-string is present in the sp

not in It is also a membership operator and does the exact reverse of in. It returns true if a partic
present in the specified string.

r/R It is used to specify the raw string. Raw strings are used in the cases where we need
meaning of escape characters such as "C://python". To define any string as a raw string, th
followed by the string.

% It is used to perform string formatting. It makes use of the format specifiers used in C pr
or %f to map their values in python. We will discuss how formatting is done in python.

Example
ADVERTISEMENT

Consider the following example to understand the real use of Python operators.

1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10. print("The string str : %s"%(str)) # prints The string str : Hello

Output:

HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello

Python String Formatting


Escape Sequence
Let's suppose we need to write the text as - They said, "Hello what's going on?"- the
given statement can be written in single quotes or double quotes but it will raise
the SyntaxError as it contains both single and double-quotes.

Example
Consider the following example to understand the real use of Python operators.

1. str = "They said, "Hello what's going on?""


2. print(str)

Output:

SyntaxError: invalid syntax

We can use the triple quotes to accomplish this problem but Python provides the
escape sequence.

The backslash(/) symbol denotes the escape sequence. The backslash can be followed
by a special character and it interpreted differently. The single quotes inside the string
must be escaped. We can apply the same as in the double quotes.

Example -

1. # using triple quotes


2. print('''''They said, "What's there?"''')
3.
4. # escaping single quotes
5. print('They said, "What\'s going on?"')
6.
7. # escaping double quotes
8. print("They said, \"What's going on?\"")

Output:

They said, "What's there?"


They said, "What's going on?"
They said, "What's going on?"

The list of an escape sequence is given below:

Sr. Escape Sequence Description Example

1. \newline It ignores the new line. print("Python1 \


Python2 \
Python3")
Output:
Python1 Python2 Python3

2. \\ Backslash print("\\")
Output:
\

3. \' Single Quotes print('\'')


Output:
'

4. \\'' Double Quotes print("\"")


Output:
"

5. \a ASCII Bell print("\a")

6. \b ASCII Backspace(BS) print("Hello \b World")


Output:
Hello World

7. \f ASCII Formfeed print("Hello \f World!"


Hello World!

8. \n ASCII Linefeed print("Hello \n World!"


Output:
Hello
World!

9. \r ASCII Carriege Return(CR) print("Hello \r World!"


Output:
World!
10. \t ASCII Horizontal Tab print("Hello \t World!"
Output:
Hello World!

11. \v ASCII Vertical Tab print("Hello \v World!"


Output:
Hello
World!

12. \ooo Character with octal value print("\110\145\154\154


Output:
Hello

13 \xHH Character with hex value. print("\x48\x65\x6c\x6c


Output:
Hello

Here is the simple example of escape sequence.

1. print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")
2. print("This is the \n multiline quotes")
3. print("This is \x48\x45\x58 representation")

Output:

C:\Users\DEVANSH SHARMA\Python32\Lib
This is the
multiline quotes
This is HEX representation

We can ignore the escape sequence from the given string by using the raw string. We
can do this by writing r or R in front of the string. Consider the following example.

1. print(r"C:\\Users\\DEVANSH SHARMA\\Python32")

Output:

C:\\Users\\DEVANSH SHARMA\\Python32

The format() method


The format() method is the most flexible and useful method in formatting strings. The
curly braces {} are used as the placeholder in the string and replaced by
the format() method argument. Let's have a look at the given an example:
1. # Using Curly braces
2. print("{} and {} both are the best friend".format("Devansh","Abhishek"))
3.
4. #Positional Argument
5. print("{1} and {0} best players ".format("Virat","Rohit"))
6.
7. #Keyword Argument
8. print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))

Output:

Devansh and Abhishek both are the best friend


Rohit and Virat best players
James,Peter,Ricky

Python String Formatting Using % Operator


Python allows us to use the format specifiers used in C's printf statement. The format
specifiers in Python are treated in the same way as they are treated in C. However,
Python provides an additional operator %, which is used as an interface between the
format specifiers and their values. In other words, we can say that it binds the format
specifiers to the values.

Consider the following example.

1. Integer = 10;
2. Float = 1.290
3. String = "Devansh"
4. print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string ...
My value is %s"%(Integer,Float,String))

Output:

Hi I am Integer ... My value is 10


Hi I am float ... My value is 1.290000
Hi I am string ... My value is Devansh

Python String functions


Python provides various in-built functions that are used for string handling. Many String
fun

Method Description

capitalize() It capitalizes the first character of the String. This


function is deprecated in python3

casefold() It returns a version of s suitable for case-less


comparisons.

center(width ,fillchar) It returns a space padded string with the original


string centred with equal number of left and right
spaces.

count(string,begin,end) It counts the number of occurrences of a substring


in a String between begin and end index.

decode(encoding = 'UTF8', errors Decodes the string using codec registered for
= 'strict') encoding.

encode() Encode S using the codec registered for encoding.


Default encoding is 'utf-8'.

endswith(suffix It returns a Boolean value if the string terminates


,begin=0,end=len(string)) with given suffix between begin and end.

expandtabs(tabsize = 8) It defines tabs in string to multiple spaces. The


default space value is 8.

find(substring ,beginIndex, It returns the index value of the string where


endIndex) substring is found between begin index and end
index.

format(value) It returns a formatted version of S, using the passed


value.

index(subsring, beginIndex, It throws an exception if string is not found. It works


endIndex) same as find() method.

isalnum() It returns true if the characters in the string are


alphanumeric i.e., alphabets or numbers and there is
at least 1 character. Otherwise, it returns false.

isalpha() It returns true if all the characters are alphabets and


there is at least one character, otherwise False.

isdecimal() It returns true if all the characters of the string are


decimals.

isdigit() It returns true if all the characters are digits and


there is at least one character, otherwise False.

isidentifier() It returns true if the string is the valid identifier.

islower() It returns true if the characters of a string are in


lower case, otherwise false.

isnumeric() It returns true if the string contains only numeric


characters.

isprintable() It returns true if all the characters of s are printable


or s is empty, false otherwise.

isupper() It returns false if characters of a string are in Upper


case, otherwise False.

isspace() It returns true if the characters of a string are white-


space, otherwise false.

istitle() It returns true if the string is titled properly and false


otherwise. A title string is the one in which the first
character is upper-case whereas the other
characters are lower-case.

isupper() It returns true if all the characters of the string(if


exists) is true otherwise it returns false.

join(seq) It merges the strings representation of the given


sequence.

len(string) It returns the length of a string.


ljust(width[,fillchar]) It returns the space padded strings with the original
string left justified to the given width.

lower() It converts all the characters of a string to Lower


case.

lstrip() It removes all leading whitespaces of a string and


can also be used to remove particular character
from leading.

partition() It searches for the separator sep in S, and returns


the part before it, the separator itself, and the part
after it. If the separator is not found, return S and
two empty strings.

maketrans() It returns a translation table to be used in translate


function.

replace(old,new[,count]) It replaces the old sequence of characters with the


new sequence. The max characters are replaced if
max is given.

rfind(str,beg=0,end=len(str)) It is similar to find but it traverses the string in


backward direction.

rindex(str,beg=0,end=len(str)) It is same as index but it traverses the string in


backward direction.

rjust(width,[,fillchar]) Returns a space padded string having original string


right justified to the number of characters specified.

rstrip() It removes all trailing whitespace of a string and can


also be used to remove particular character from
trailing.

rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string from
the backward direction. It returns the list of words in
the string. If Separator is not specified then the
string splits according to the white-space.

split(str,num=string.count(str)) Splits the string according to the delimiter str. The


string splits according to the space if the delimiter is
not provided. It returns the list of substring
concatenated with the delimiter.

splitlines(num=string.count('\n')) It returns the list of strings at each line with newline


removed.

startswith(str,beg=0,end=len(str)) It returns a Boolean value if the string starts with


given str between begin and end.

strip([chars]) It is used to perform lstrip() and rstrip() on the


string.

swapcase() It inverts case of all characters in a string.

title() It is used to convert the string into the title-case i.e.,


The string meEruT will be converted to Meerut.

translate(table,deletechars = '') It translates the string according to the translation


table passed in the function .

upper() It converts all the characters of a string to Upper


Case.

zfill(width) Returns original string leftpadded with zeros to a


total of width characters; intended for numbers,
zfill() retains any sign given (less one zero).

rpartition()

Python lists are mutable, we can change their elements after forming. The comma (,) and
the square brackets [enclose the List's items] serve as separators.

Although six Python data types can hold sequences, the List is the most common and
reliable form. A list, a type of sequence data, is used to store the collection of data.
Tuples and Strings are two similar data formats for sequences.

Lists written in Python are identical to dynamically scaled arrays defined in other
languages, such as Array List in Java and Vector in C++. A list is a collection of items
separated by commas and denoted by the symbol [].
List Declaration
Code

ADVERTISEMENT

1. # a simple list
2. list1 = [1, 2, "Python", "Program", 15.9]
3. list2 = ["Amy", "Ryan", "Henry", "Emma"]
4.
5. # printing the list
6. print(list1)
7. print(list2)
8.
9. # printing the type of list
10. print(type(list1))
11. print(type(list2))

Output:

[1, 2, 'Python', 'Program', 15.9]


['Amy', 'Ryan', 'Henry', 'Emma']
< class ' list ' >
< class ' list ' >

Characteristics of Lists
The characteristics of the List are as follows:

ADVERTISEMENT

o The lists are in order.


o The list element can be accessed via the index.
o The mutable type of List is
o The rundowns are changeable sorts.
o The number of various elements can be stored in a list.

Ordered List Checking


Code
1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
3. b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
4. a == b

Output:

False

The indistinguishable components were remembered for the two records; however, the
subsequent rundown changed the file position of the fifth component, which is against
the rundowns' planned request. False is returned when the two lists are compared.

Code

1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
3. b = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6]
4. a == b

Output:

True

Records forever protect the component's structure. Because of this, it is an arranged


collection of things.

Let's take a closer look at the list example.

Code

1. # list example in detail


2. emp = [ "John", 102, "USA"]
3. Dep1 = [ "CS",10]
4. Dep2 = [ "IT",11]
5. HOD_CS = [ 10,"Mr. Holding"]
6. HOD_IT = [11, "Mr. Bewon"]
7. print("printing employee data ...")
8. print(" Name : %s, ID: %d, Country: %s" %(emp[0], emp[1], emp[2]))
9. print("printing departments ...")
10. print("Department 1:\nName: %s, ID: %d\n Department 2:\n Name: %s, ID: %s"%( Dep1[
0], Dep2[1], Dep2[0], Dep2[1]))
11. print("HOD Details ....")
12. print("CS HOD Name: %s, Id: %d" %(HOD_CS[1], HOD_CS[0]))
13. print("IT HOD Name: %s, Id: %d" %(HOD_IT[1], HOD_IT[0]))
14. print(type(emp), type(Dep1), type(Dep2), type(HOD_CS), type(HOD_IT))

Output:

printing employee data...


Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class ' list '> <class ' list '> <class ' list '> <class ' list '> <class '
list '>

In the preceding illustration, we printed the employee and department-specific details


from lists that we had created. To better comprehend the List's concept, look at the
code above.

List Indexing and Splitting


The indexing procedure is carried out similarly to string processing. The slice operator []
can be used to get to the List's components.

The index ranges from 0 to length -1. The 0th index is where the List's first element is
stored; the 1st index is where the second element is stored, and so on.
We can get the sub-list of the list using the following syntax.

1. list_varible(start:stop:step)

o The beginning indicates the beginning record position of the rundown.


o The stop signifies the last record position of the rundown.
o Within a start, the step is used to skip the nth element: stop.

The start parameter is the initial index, the step is the ending index, and the value of the
end parameter is the number of elements that are "stepped" through. The default value
for the step is one without a specific value. Inside the resultant Sub List, the same with
record start would be available, yet the one with the file finish will not. The first element
in a list appears to have an index of zero.

Consider the following example:

Code

1. list = [1,2,3,4,5,6,7]
2. print(list[0])
3. print(list[1])
4. print(list[2])
5. print(list[3])
6. # Slicing the elements
7. print(list[0:6])
8. # By default, the index value is 0 so its starts from the 0th element and go for index -
1.
9. print(list[:])
10. print(list[2:5])
11. print(list[1:6:2])
ADVERTISEMENT

Output:

1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]

In contrast to other programming languages, Python lets you use negative indexing as
well. The negative indices are counted from the right. The index -1 represents the final
element on the List's right side, followed by the index -2 for the next member on the
left, and so on, until the last element on the left is reached.

Let's have a look at the following example where we will use negative indexing to access
the elements of the list.

Code
1. # negative indexing example
2. list = [1,2,3,4,5]
3. print(list[-1])
4. print(list[-3:])
5. print(list[:-1])
6. print(list[-3:-1])

Output:

5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]

Negative indexing allows us to obtain an element, as previously mentioned. The


rightmost item in the List was returned by the first print statement in the code above.
The second print statement returned the sub-list, and so on.

Updating List Values


ADVERTISEMENT
ADVERTISEMENT

Due to their mutability and the slice and assignment operator's ability to update their
values, lists are Python's most adaptable data structure. Python's append() and insert()
methods can also add values to a list.

Consider the following example to update the values inside the List.

Code

1. # updating list values


2. list = [1, 2, 3, 4, 5, 6]
3. print(list)
4. # It will assign value to the value to the second index
5. list[2] = 10
6. print(list)
7. # Adding multiple-element
8. list[1:3] = [89, 78]
9. print(list)
10. # It will add value at the end of the list
11. list[-1] = 25
12. print(list)

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

The list elements can also be deleted by using the del keyword. Python also provides us
the remove() method if we do not know which element is to be deleted from the list.

Consider the following example to delete the list elements.

Code

1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
3. # It will assign value to the value to second index
4. list[2] = 10
5. print(list)
6. # Adding multiple element
7. list[1:3] = [89, 78]
8. print(list)
9. # It will add value at the end of the list
10. list[-1] = 25
11. print(list)

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

Python List Operations


The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings. The different operations of list are
1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership

Let's see how the list responds to various operators.

1. Repetition
The redundancy administrator empowers the rundown components to be rehashed on
different occasions.

Code

1. # repetition of list
2. # declaring the list
3. list1 = [12, 14, 16, 18, 20]
4. # repetition operator *
5. l = list1 * 2
6. print(l)

Output:

[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]

2. Concatenation
It concatenates the list mentioned on either side of the operator.

Code

1. # concatenation of two lists


2. # declaring the lists
3. list1 = [12, 14, 16, 18, 20]
4. list2 = [9, 10, 32, 54, 86]
5. # concatenation operator +
6. l = list1 + list2
7. print(l)

Output:

[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]

3. Length
It is used to get the length of the list

Code

1. # size of the list


2. # declaring the list
3. list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
4. # finding length of the list
5. len(list1)

Output:

4. Iteration
The for loop is used to iterate over the list elements.

Code

1. # iteration of the list


2. # declaring the list
3. list1 = [12, 14, 16, 39, 40]
4. # iterating
5. for i in list1:
6. print(i)

Output:

12
14
16
39
40

5. Membership
It returns true if a particular item exists in a particular list otherwise false.

Code

1. # membership of the list


2. # declaring the list
3. list1 = [100, 200, 300, 400, 500]
4. # true will be printed if value exists
5. # and false if not
6.
7. print(600 in list1)
8. print(700 in list1)
9. print(1040 in list1)
10.
11. print(300 in list1)
12. print(100 in list1)
13. print(500 in list1)

Output:

False
False
False
True
True
True

Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings, which
can be iterated as follows.

Code

ADVERTISEMENT

1. # iterating a list
2. list = ["John", "David", "James", "Jonathan"]
3. for i in list:
4. # The i variable will iterate over the elements of the List and contains each element in
each iteration.
5. print(i)

Output:

John
David
James
Jonathan

Adding Elements to the List


The append() function in Python can add a new item to the List. In any case, the annex()
capability can enhance the finish of the rundown.

Consider the accompanying model, where we take the components of the rundown
from the client and print the rundown on the control center.

Code

1. #Declaring the empty list


2. l =[]
3. #Number of elements will be entered by the user
4. n = int(input("Enter the number of elements in the list:"))
5. # for loop to take the input
6. for i in range(0,n):
7. # The input is taken from the user and added to the list as the item
8. l.append(input("Enter the item:"))
9. print("printing the list items..")
10. # traversal loop to print the list items
11. for i in l:
12. print(i, end = " ")

Output:

ADVERTISEMENT
Enter the number of elements in the list:10
Enter the item:32
Enter the item:56
Enter the item:81
Enter the item:2
Enter the item:34
Enter the item:65
Enter the item:09
Enter the item:66
Enter the item:12
Enter the item:18
printing the list items..
32 56 81 2 34 65 09 66 12 18

Removing Elements from the List


The remove() function in Python can remove an element from the List. To comprehend
this idea, look at the example that follows.

Example -

Code

1. list = [0,1,2,3,4]
2. print("printing original list: ");
3. for i in list:
4. print(i,end=" ")
5. list.remove(2)
6. print("\nprinting the list after the removal of first element...")
7. for i in list:
8. print(i,end=" ")

Output:

printing original list:


0 1 2 3 4
printing the list after the removal of first element...
0 1 3 4

Python List Built-in Functions


Python provides the following built-in functions, which can be used with the lists.

1. len()
2. max()
3. min()

len( )
It is used to calculate the length of the list.

Code

1. # size of the list


2. # declaring the list
3. list1 = [12, 16, 18, 20, 39, 40]
4. # finding length of the list
5. len(list1)

Output:

Max( )
It returns the maximum element of the list

Code

1. # maximum of the list


2. list1 = [103, 675, 321, 782, 200]
3. # large element in the list
4. print(max(list1))

Output:

782

Min( )
It returns the minimum element of the list

Code
1. # minimum of the list
2. list1 = [103, 675, 321, 782, 200]
3. # smallest element in the list
4. print(min(list1))

Output:

103

Let's have a look at the few list examples.

Example: 1- Create a program to eliminate the List's duplicate items.

Code

1. list1 = [1,2,2,3,55,98,65,65,13,29]
2. # Declare an empty list that will store unique values
3. list2 = []
4. for i in list1:
5. if i not in list2:
6. list2.append(i)
7. print(list2)

Output:

[1, 2, 3, 55, 98, 65, 13, 29]

Example:2- Compose a program to track down the amount of the component in the
rundown.

Code

1. list1 = [3,4,5,9,10,12,24]
2. sum = 0
3. for i in list1:
4. sum = sum+i
5. print("The sum is:",sum)

Output:
The sum is: 67
In [8]:

Example: 3- Compose the program to find the rundowns comprise of somewhere


around one normal component.

Code

1. list1 = [1,2,3,4,5,6]
2. list2 = [7,8,9,2,10]
3. for x in list1:
4. for y in list2:
5. if x == y:
6. print("The common element is:",x)

Output:

The common element is: 2

Python Tuples
A comma-separated group of items is called a Python triple. The ordering, settled items,
and reiterations of a tuple are to some degree like those of a rundown, but in contrast
to a rundown, a tuple is unchanging.

The main difference between the two is that we cannot alter the components of a tuple
once they have been assigned. On the other hand, we can edit the contents of a list.

Example

1. ("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.

Features of Python Tuple


ADVERTISEMENT
ADVERTISEMENT

o Tuples are an immutable data type, meaning their elements cannot be changed
after they are generated.
o Each element in a tuple has a specific order that will never change because tuples
are ordered sequences.

Forming a Tuple:
All the objects-also known as "elements"-must be separated by a comma, enclosed in
parenthesis (). Although parentheses are not required, they are recommended.

ADVERTISEMENT

Any number of items, including those with various data types (dictionary, string, float,
list, etc.), can be contained in a tuple.

Code

1. # Python program to show how to create a tuple


2. # Creating an empty tuple
3. empty_tuple = ()
4. print("Empty tuple: ", empty_tuple)
5.
6. # Creating tuple having integers
7. int_tuple = (4, 6, 8, 10, 12, 14)
8. print("Tuple with integers: ", int_tuple)
9.
10. # Creating a tuple having objects of different data types
11. mixed_tuple = (4, "Python", 9.3)
12. print("Tuple with different data types: ", mixed_tuple)
13.
14. # Creating a nested tuple
15. nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
16. print("A nested tuple: ", nested_tuple)

Output:

Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Parentheses are not necessary for the construction of multiples. This is known as triple
pressing.

Code

1. # Python program to create a tuple without using parentheses


2. # Creating a tuple
3. tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]
4. # Displaying the tuple created
5. print(tuple_)
6. # Checking the data type of object tuple_
7. print(type(tuple_) )
8. # Trying to modify tuple_
9. try:
10. tuple_[1] = 4.2
11. except:
12. print(TypeError )

Output:

(4, 5.7, 'Tuples', ['Python', 'Tuples'])


<class 'tuple'>
<class 'TypeError'>

The development of a tuple from a solitary part may be complex.

Essentially adding a bracket around the component is lacking. A comma must separate
the element to be recognized as a tuple.

Code

1. # Python program to show how to create a tuple having a single element


2. single_tuple = ("Tuple")
3. print( type(single_tuple) )
4. # Creating a tuple that has only one element
5. single_tuple = ("Tuple",)
6. print( type(single_tuple) )
7. # Creating tuple without parentheses
8. single_tuple = "Tuple",
9. print( type(single_tuple) )

Output:

<class 'str'>
<class 'tuple'>
<class 'tuple'>

Accessing Tuple Elements


A tuple's objects can be accessed in a variety of ways.

Indexing

Indexing We can use the index operator [] to access an object in a tuple, where the
index starts at 0.

ADVERTISEMENT

The indices of a tuple with five items will range from 0 to 4. An Index Error will be raised
assuming we attempt to get to a list from the Tuple that is outside the scope of the
tuple record. An index above four will be out of range in this scenario.

Because the index in Python must be an integer, we cannot provide an index of a


floating data type or any other type. If we provide a floating index, the result will be
TypeError.

The method by which elements can be accessed through nested tuples can be seen in
the example below.

Code

1. # Python program to show how to access tuple elements


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Collection")
4. print(tuple_[0])
5. print(tuple_[1])
6. # trying to access element index more than the length of a tuple
7. try:
8. print(tuple_[5])
9. except Exception as e:
10. print(e)
11. # trying to access elements through the index of floating data type
12. try:
13. print(tuple_[1.0])
14. except Exception as e:
15. print(e)
16. # Creating a nested tuple
17. nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))
18.
19. # Accessing the index of a nested tuple
20. print(nested_tuple[0][3])
21. print(nested_tuple[1][1])

Output:

Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6

o Negative Indexing

ADVERTISEMENT

Python's sequence objects support negative indexing.

The last thing of the assortment is addressed by - 1, the second last thing by - 2, etc.

Code

1. # Python program to show how negative indexing works in Python tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Collection")
4. # Printing elements using negative indices
5. print("Element at -1 index: ", tuple_[-1])
6. print("Elements between -4 and -1 are: ", tuple_[-4:-1])
Output:

Element at -1 index: Collection


Elements between -4 and -1 are: ('Python', 'Tuple', 'Ordered')

Slicing
Tuple slicing is a common practice in Python and the most common way for
programmers to deal with practical issues. Look at a tuple in Python. Slice a tuple to
access a variety of its elements. Using the colon as a straightforward slicing operator (:)
is one strategy.

To gain access to various tuple elements, we can use the slicing operator colon (:).

ADVERTISEMENT

Code

1. # Python program to show how slicing works in Python tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
4. # Using slicing to access elements of the tuple
5. print("Elements between indices 1 and 3: ", tuple_[1:3])
6. # Using negative indexing in slicing
7. print("Elements between indices 0 and -4: ", tuple_[:-4])
8. # Printing the entire tuple by using the default start and end values.
9. print("Entire tuple: ", tuple_[:])

Output:

Elements between indices 1 and 3: ('Tuple', 'Ordered')


Elements between indices 0 and -4: ('Python', 'Tuple')
Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection',
'Objects')

Deleting a Tuple
A tuple's parts can't be modified, as was recently said. We are unable to eliminate or
remove tuple components as a result.

However, the keyword del can completely delete a tuple.


Code

1. # Python program to show how to delete elements of a Python tuple


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
4. # Deleting a particular element of the tuple
5. try:
6. del tuple_[3]
7. print(tuple_)
8. except Exception as e:
9. print(e)
10. # Deleting the variable from the global space of the program
11. del tuple_
12. # Trying accessing the tuple after deleting it
13. try:
14. print(tuple_)
15. except Exception as e:
16. print(e)

Output:

'tuple' object does not support item deletion


name 'tuple_' is not defined

Repetition Tuples in Python


Code

ADVERTISEMENT

1. # Python program to show repetition in tuples


2. tuple_ = ('Python',"Tuples")
3. print("Original tuple is: ", tuple_)
4. # Repeting the tuple elements
5. tuple_ = tuple_ * 3
6. print("New tuple is: ", tuple_)

Output:
Original tuple is: ('Python', 'Tuples')
New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')

Tuple Methods
Like the list, Python Tuples is a collection of immutable objects. There are a few ways to
work with tuples in Python. With some examples, this essay will go over these two
approaches in detail.

The following are some examples of these methods.

o Count () Method

The times the predetermined component happens in the Tuple is returned by the count
() capability of the Tuple.

Code

1. # Creating tuples
2. T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
3. T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
4. # counting the appearance of 3
5. res = T1.count(2)
6. print('Count of 2 in T1 is:', res)
7. # counting the appearance of java
8. res = T2.count('java')
9. print('Count of Java in T2 is:', res)

Output:

ADVERTISEMENT
ADVERTISEMENT

Count of 2 in T1 is: 5
Count of java in T2 is: 2

Index() Method:
The Index() function returns the first instance of the requested element from the Tuple.

Parameters:
o The thing that must be looked for.
o Start: (Optional) the index that is used to begin the final (optional) search: The
most recent index from which the search is carried out
o Index Method

Code

1. # Creating tuples
2. Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
3. # getting the index of 3
4. res = Tuple_data.index(3)
5. print('First occurrence of 1 is', res)
6. # getting the index of 3 after 4th
7. # index
8. res = Tuple_data.index(3, 4)
9. print('First occurrence of 1 after 4th index is:', res)

Output:

First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6

Tuple Membership Test


Utilizing the watchword, we can decide whether a thing is available in the given Tuple.

Code

1. # Python program to show how to perform membership test for tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
4. # In operator
5. print('Tuple' in tuple_)
6. print('Items' in tuple_)
7. # Not in operator
8. print('Immutable' not in tuple_)
9. print('Items' not in tuple_)
Output:

True
False
False
True

Iterating Through a Tuple


A for loop can be used to iterate through each tuple element.

Code

1. # Python program to show how to iterate over tuple elements


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
4. # Iterating over tuple elements using a for loop
5. for item in tuple_:
6. print(item)

Output:

Python
Tuple
Ordered
Immutable

Changing a Tuple
Tuples, instead of records, are permanent articles.

This suggests that once the elements of a tuple have been defined, we cannot change
them. However, the nested elements can be altered if the element itself is a changeable
data type like a list.

Multiple values can be assigned to a tuple through reassignment.

Code

ADVERTISEMENT

1. # Python program to show that Python tuples are immutable objects


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", [1,2,3,4])
4. # Trying to change the element at index 2
5. try:
6. tuple_[2] = "Items"
7. print(tuple_)
8. except Exception as e:
9. print( e )
10. # But inside a tuple, we can change elements of a mutable object
11. tuple_[-1][2] = 10
12. print(tuple_)
13. # Changing the whole tuple
14. tuple_ = ("Python", "Items")
15. print(tuple_)

Output:

'tuple' object does not support item assignment


('Python', 'Tuple', 'Ordered', 'Immutable', [1, 2, 10, 4])
('Python', 'Items')

The + operator can be used to combine multiple tuples into one. This phenomenon is
known as concatenation.

We can also repeat the elements of a tuple a predetermined number of times by using
the * operator. This is already demonstrated above.

The aftereffects of the tasks + and * are new tuples.

Code

1. # Python program to show how to concatenate tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
4. # Adding a tuple to the tuple_
5. print(tuple_ + (4, 5, 6))

Output:

('Python', 'Tuple', 'Ordered', 'Immutable', 4, 5, 6)


Tuples have the following advantages over lists:

o Triples take less time than lists do.


o Due to tuples, the code is protected from accidental modifications. It is desirable
to store non-changing information in "tuples" instead of "records" if a program
expects it.
o A tuple can be used as a dictionary key if it contains immutable values like
strings, numbers, or another tuple. "Lists" cannot be utilized as dictionary keys
because they are mutable.

Python Set
A Python set is the collection of the unordered items. Each element in the set must be
unique, immutable, and the sets remove the duplicate elements. Sets are mutable which
means we can modify it after its creation.

Unlike other collections in Python, there is no index attached to the elements of the set,
i.e., we cannot directly access any element of the set by the index. However, we can print
them all together, or we can get the list of elements by looping through the set.

Creating a set
The set can be created by enclosing the comma-separated immutable items with the
curly braces {}. Python also provides the set() method, which can be used to create the
set by the passed sequence.

Example 1: Using curly braces

1. Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}

2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)

Output:
ADVERTISEMENT

ADVERTISEMENT

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday',


'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday

Example 2: Using set() method

1. Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunda


y"])
2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)

Output:

{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday',


'Sunday'}
<class 'set'>
looping through the set elements ...
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday

It can contain any type of element such as integer, float, tuple etc. But mutable elements
(list, dictionary, set) can't be a member of set. Consider the following example.

1. # Creating a set which have immutable elements


2. set1 = {1,2,3, "JavaTpoint", 20.5, 14}
3. print(type(set1))
4. #Creating a set which have mutable element
5. set2 = {1,2,3,["Javatpoint",4]}
6. print(type(set2))

Output:

<class 'set'>

Traceback (most recent call last)


<ipython-input-5-9605bb6fbc68> in <module>
4
5 #Creating a set which holds mutable elements
----> 6 set2 = {1,2,3,["Javatpoint",4]}
7 print(type(set2))

TypeError: unhashable type: 'list'

In the above code, we have created two sets, the set set1 have immutable elements and
set2 have one mutable element as a list. While checking the type of set2, it raised an
error, which means set can contain only immutable elements.

Creating an empty set is a bit different because empty curly {} braces are also used to
create a dictionary as well. So Python provides the set() method used without an
argument to create an empty set.

1. # Empty curly braces will create dictionary


2. set3 = {}
3. print(type(set3))
4.
5. # Empty set using set() function
6. set4 = set()
7. print(type(set4))

Output:

ADVERTISEMENT
ADVERTISEMENT

<class 'dict'>
<class 'set'>

Let's see what happened if we provide the duplicate element to the set.

1. set5 = {1,2,4,4,5,8,9,9,10}
2. print("Return set with unique elements:",set5)
Output:

Return set with unique elements: {1, 2, 4, 5, 8, 9, 10}

In the above code, we can see that set5 consisted of multiple duplicate elements when
we printed it remove the duplicity from the set.

Adding items to the set


Python provides the add() method and update() method which can be used to add
some particular item to the set. The add() method is used to add a single element
whereas the update() method is used to add multiple elements to the set. Consider the
following example.

Example: 1 - Using add() method

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(months)
4. print("\nAdding other months to the set...");
5. Months.add("July");
6. Months.add ("August");
7. print("\nPrinting the modified set...");
8. print(Months)
9. print("\nlooping through the set elements ... ")
10. for i in Months:
11. print(i)

Output:

printing the original set ...


{'February', 'May', 'April', 'March', 'June', 'January'}

Adding other months to the set...

Printing the modified set...


{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}

looping through the set elements ...


February
July
May
April
March
August
June
January

To add more than one item in the set, Python provides the update() method. It accepts
iterable as an argument.

Consider the following example.

ADVERTISEMENT

Example - 2 Using update() function

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nupdating the original set ... ")
5. Months.update(["July","August","September","October"]);
6. print("\nprinting the modified set ... ")
7. print(Months);

Output:

printing the original set ...


{'January', 'February', 'April', 'May', 'June', 'March'}

updating the original set ...


printing the modified set ...
{'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July',
'September', 'March'}

Removing items from the set


Python provides the discard() method and remove() method which can be used to
remove the items from the set. The difference between these function, using discard()
function if the item does not exist in the set then the set remain unchanged whereas
remove() method will through an error.

Consider the following example.

ADVERTISEMENT

Example-1 Using discard() method


1. months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(months)
4. print("\nRemoving some months from the set...");
5. months.discard("January");
6. months.discard("May");
7. print("\nPrinting the modified set...");
8. print(months)
9. print("\nlooping through the set elements ... ")
10. for i in months:
11. print(i)

Output:

printing the original set ...


{'February', 'January', 'March', 'April', 'June', 'May'}

Removing some months from the set...

Printing the modified set...


{'February', 'March', 'April', 'June'}

looping through the set elements ...


February
March
April
June

Python provides also the remove() method to remove the item from the set. Consider
the following example to remove the items using remove() method.

Example-2 Using remove() function

1. months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(months)
4. print("\nRemoving some months from the set...");
5. months.remove("January");
6. months.remove("May");
7. print("\nPrinting the modified set...");
8. print(months)
ADVERTISEMENT
ADVERTISEMENT

Output:

printing the original set ...


{'February', 'June', 'April', 'May', 'January', 'March'}

Removing some months from the set...

Printing the modified set...


{'February', 'June', 'April', 'March'}

We can also use the pop() method to remove the item. Generally, the pop() method will
always remove the last item but the set is unordered, we can't determine which element
will be popped from set.

Consider the following example to remove the item from the set using pop() method.

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving some months from the set...");
5. Months.pop();
6. Months.pop();
7. print("\nPrinting the modified set...");
8. print(Months)

Output:

printing the original set ...


{'June', 'January', 'May', 'April', 'February', 'March'}

Removing some months from the set...

Printing the modified set...


{'May', 'April', 'February', 'March'}

In the above code, the last element of the Month set is March but the pop() method
removed the June and January because the set is unordered and the pop() method
could not determine the last element of the set.

Python provides the clear() method to remove all the items from the set.

ADVERTISEMENT
ADVERTISEMENT

Consider the following example.

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving all the items from the set...");
5. Months.clear()
6. print("\nPrinting the modified set...")
7. print(Months)

Output:

printing the original set ...


{'January', 'May', 'June', 'April', 'March', 'February'}

Removing all the items from the set...

Printing the modified set...


set()

Difference between discard() and remove()


Despite the fact that discard() and remove() method both perform the same task,
There is one main difference between discard() and remove().

If the key to be deleted from the set using discard() doesn't exist in the set, the Python
will not give the error. The program maintains its control flow.

On the other hand, if the item to be deleted from the set using remove() doesn't exist in
the set, the Python will raise an error.

Consider the following example.

Example-

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving items through discard() method...");
5. Months.discard("Feb"); #will not give an error although the key feb is not available in the
set
6. print("\nprinting the modified set...")
7. print(Months)
8. print("\nRemoving items through remove() method...");
9. Months.remove("Jan") #will give an error as the key jan is not available in the set.
10. print("\nPrinting the modified set...")
11. print(Months)

Output:

ADVERTISEMENT

printing the original set ...


{'March', 'January', 'April', 'June', 'February', 'May'}

Removing items through discard() method...

printing the modified set...


{'March', 'January', 'April', 'June', 'February', 'May'}

Removing items through remove() method...


Traceback (most recent call last):
File "set.py", line 9, in
Months.remove("Jan")
KeyError: 'Jan'
ADVERTISEMENT

Python Set Operations


Set can be performed mathematical operation such as union, intersection, difference,
and symmetric difference. Python provides the facility to carry out these operations with
operators or methods. We describe these operations as follows.

Union of two Sets


To combine two or more sets into one set in Python, use the union() function. All of the
distinctive characteristics from each combined set are present in the final set. As
parameters, one or more sets may be passed to the union() function. The function
returns a copy of the set supplied as the lone parameter if there is just one set. The
method returns a new set containing all the different items from all the arguments if
more than one set is supplied as an argument.
Consider the following example to calculate the union of two sets.

Example 1: using union | operator

1. Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}


2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1|Days2) #printing the union of the sets

Output:

{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday',


'Thursday'}

Python also provides the union() method which can also be used to calculate the union
of two sets. Consider the following example.

ADVERTISEMENT

Example 2: using union() method

1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1.union(Days2)) #printing the union of the sets

Output:

{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday',


'Saturday'}
Now, we can also make the union of more than two sets using the union() function, for
example:

Program:

1. # Create three sets


2. set1 = {1, 2, 3}
3. set2 = {2, 3, 4}
4. set3 = {3, 4, 5}
5.
6. # Find the common elements between the three sets
7. common_elements = set1.union(set2, set3)
8.
9. # Print the common elements
10. print(common_elements)

Output:

{1, 2, 3, 4, 5}

The intersection of two sets


To discover what is common between two or more sets in Python, apply the
intersection() function. Only the items in all sets being compared are included in the
final set. One or more sets can also be used as the intersection() function parameters.
The function returns a copy of the set supplied as the lone parameter if there is just one
set. The method returns a new set that only contains the elements in all the compared
sets if multiple sets are supplied as arguments.

The intersection of two sets can be performed by the and & operator or
the intersection() function. The intersection of the two sets is given as the set of the
elements that common in both sets.
Consider the following example.

Example 1: Using & operator

1. Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday","Tuesday","Sunday", "Friday"}
3. print(Days1&Days2) #prints the intersection of the two sets

Output:

{'Monday', 'Tuesday'}

Example 2: Using intersection() method

1. set1 = {"Devansh","John", "David", "Martin"}


2. set2 = {"Steve", "Milan", "David", "Martin"}
3. print(set1.intersection(set2)) #prints the intersection of the two sets

Output:

{'Martin', 'David'}

Example 3:

1. set1 = {1,2,3,4,5,6,7}
2. set2 = {1,2,20,32,5,9}
3. set3 = set1.intersection(set2)
4. print(set3)

Output:

ADVERTISEMENT

{1,2,5}

Similarly, as the same as union function, we can perform the intersection of more than
two sets at a time,

For Example:

Program

1. # Create three sets


2. set1 = {1, 2, 3}
3. set2 = {2, 3, 4}
4. set3 = {3, 4, 5}
5.
6. # Find the common elements between the three sets
7. common_elements = set1.intersection(set2, set3)
8.
9. # Print the common elements
10. print(common_elements)

Output:

{3}

The intersection_update() method


The intersection_update() method removes the items from the original set that are not
present in both the sets (all the sets if more than one are specified).

ADVERTISEMENT

The intersection_update() method is different from the intersection() method since it


modifies the original set by removing the unwanted items, on the other hand, the
intersection() method returns a new set.
Consider the following example.

1. a = {"Devansh", "bob", "castle"}


2. b = {"castle", "dude", "emyway"}
3. c = {"fuson", "gaurav", "castle"}
4.
5. a.intersection_update(b, c)
6.
7. print(a)

Output:

{'castle'}

Difference between the two sets


The difference of two sets can be calculated by using the subtraction (-) operator
or intersection() method. Suppose there are two sets A and B, and the difference is A-B
that denotes the resulting set will be obtained that element of A, which is not present in
the set B.

Consider the following example.

Example 1 : Using subtraction ( - ) operator

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday", "Tuesday", "Sunday"}
3. print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}

Output:

{'Thursday', 'Wednesday'}

Example 2 : Using difference() method

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday", "Tuesday", "Sunday"}
3. print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2

Output:

{'Thursday', 'Wednesday'}

Symmetric Difference of two sets


In Python, the symmetric Difference between set1 and set2 is the set of elements
present in one set or the other but not in both sets. In other words, the set of elements
is in set1 or set2 but not in their intersection.

The Symmetric Difference of two sets can be computed using Python's


symmetric_difference() method. This method returns a new set containing all the
elements in either but not in both. Consider the following example:
Example - 1: Using ^ operator

ADVERTISEMENT

1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a^b
4. print(c)

Output:

{3, 4, 5, 6, 8, 9, 10}

Example - 2: Using symmetric_difference() method

1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a.symmetric_difference(b)
4. print(c)

Output:

{3, 4, 5, 6, 8, 9, 10}

Set comparisons
In Python, you can compare sets to check if they are equal, if one set is a subset or
superset of another, or if two sets have elements in common.

Here are the set comparison operators available in Python:

ADVERTISEMENT

o ==: checks if two sets have the same elements, regardless of their order.
o !=: checks if two sets are not equal.
o <: checks if the left set is a proper subset of the right set (i.e., all elements in the
left set are also in the right set, but the right set has additional elements).
o <=: checks if the left set is a subset of the right set (i.e., all elements in the left set
are also in the right set).
o >: checks if the left set is a proper superset of the right set (i.e., all elements in the
right set are also in the left set, but the left set has additional elements).
o >=: checks if the left set is a superset of the right set (i.e., all elements in the right
set are also in the left).

Consider the following example.

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday", "Tuesday"}
3. Days3 = {"Monday", "Tuesday", "Friday"}
4.
5. #Days1 is the superset of Days2 hence it will print true.
6. print (Days1>Days2)
7.
8. #prints false since Days1 is not the subset of Days2
9. print (Days1<Days2)
10.
11. #prints false since Days2 and Days3 are not equivalent
12. print (Days2 == Days3)

Output:

True
False
False
FrozenSets
In Python, a frozen set is an immutable version of the built-in set data type. It is similar
to a set, but its contents cannot be changed once a frozen set is created.

Frozen set objects are unordered collections of unique elements, just like sets. They can
be used the same way as sets, except they cannot be modified. Because they are
immutable, frozen set objects can be used as elements of other sets or dictionary keys,
while standard sets cannot.

One of the main advantages of using frozen set objects is that they are hashable,
meaning they can be used as keys in dictionaries or as elements of other sets. Their
contents cannot change, so their hash values remain constant. Standard sets are not
hashable because they can be modified, so their hash values can change.

Frozen set objects support many of the assets of the same operation, such as union,
intersection, Difference, and symmetric Difference. They also support operations that do
not modify the frozen set, such as len(), min(), max(), and in.

Consider the following example to create the frozen set.

1. Frozenset = frozenset([1,2,3,4,5])
2. print(type(Frozenset))
3. print("\nprinting the content of frozen set...")
4. for i in Frozenset:
5. print(i);
6. Frozenset.add(6) #gives an error since we cannot change the content of Frozenset after
creation

Output:

<class 'frozenset'>

printing the content of frozen set...


1
2
3
4
5
Traceback (most recent call last):
File "set.py", line 6, in <module>
Frozenset.add(6) #gives an error since we can change the content of
Frozenset after creation
AttributeError: 'frozenset' object has no attribute 'add'

Frozenset for the dictionary


If we pass the dictionary as the sequence inside the frozenset() method, it will take only
the keys from the dictionary and returns a frozenset that contains the key of the
dictionary as its elements.

Consider the following example.

1. Dictionary = {"Name":"John", "Country":"USA", "ID":101}


2. print(type(Dictionary))
3. Frozenset = frozenset(Dictionary); #Frozenset will contain the keys of the dictionary
4. print(type(Frozenset))
5. for i in Frozenset:
6. print(i)

Output:

<class 'dict'>
<class 'frozenset'>
Name
Country
ID

Set Programming Example


Example - 1: Write a program to remove the given number from the set.

1. my_set = {1,2,3,4,5,6,12,24}
2. n = int(input("Enter the number you want to remove"))
3. my_set.discard(n)
4. print("After Removing:",my_set)

Output:

Enter the number you want to remove:12


After Removing: {1, 2, 3, 4, 5, 6, 24}

Example - 2: Write a program to add multiple elements to the set.

1. set1 = set([1,2,4,"John","CS"])
2. set1.update(["Apple","Mango","Grapes"])
3. print(set1)

Output:

{1, 2, 4, 'Apple', 'John', 'CS', 'Mango', 'Grapes'}

Example - 3: Write a program to find the union between two set.

1. set1 = set(["Peter","Joseph", 65,59,96])


2. set2 = set(["Peter",1,2,"Joseph"])
3. set3 = set1.union(set2)
4. print(set3)

Output:

{96, 65, 2, 'Joseph', 1, 'Peter', 59}

Example- 4: Write a program to find the intersection between two sets.

1. set1 = {23,44,56,67,90,45,"Javatpoint"}
2. set2 = {13,23,56,76,"Sachin"}
3. set3 = set1.intersection(set2)
4. print(set3)

Output:

{56, 23}

Example - 5: Write the program to add element to the frozenset.

1. set1 = {23,44,56,67,90,45,"Javatpoint"}
2. set2 = {13,23,56,76,"Sachin"}
3. set3 = set1.intersection(set2)
4. print(set3)

Output:

TypeError: 'frozenset' object does not support item assignment


Above code raised an error because frozensets are immutable and can't be changed
after creation.

Example - 6: Write the program to find the issuperset, issubset and superset.

1. set1 = set(["Peter","James","Camroon","Ricky","Donald"])
2. set2 = set(["Camroon","Washington","Peter"])
3. set3 = set(["Peter"])
4.
5. issubset = set1 >= set2
6. print(issubset)
7. issuperset = set1 <= set2
8. print(issuperset)
9. issubset = set3 <= set2
10. print(issubset)
11. issuperset = set2 >= set3
12. print(issuperset)

Output:

False
False
True
True

Python Built-in set methods


Python contains the following methods to be used with the sets.

SN Method Description

1 add(item) It adds an item to the set. It has no effect if the item is already

2 clear() It deletes all the items from the set.

3 copy() It returns a shallow copy of the set.

4 difference_update(....) It modifies this set by removing all the items that are also pres
sets.

5 discard(item) It removes the specified item from the set.

6 intersection() It returns a new set that contains only the common elements
the sets if more than two are specified).

7 intersection_update(....) It removes the items from the original set that are not prese
(all the sets if more than one are specified).

8 Isdisjoint(....) Return True if two sets have a null intersection.

9 Issubset(....) Report whether another set contains this set.

10 Issuperset(....) Report whether this set contains another set.

11 pop() Remove and return an arbitrary set element that is the last
Raises KeyError if the set is empty.

12 remove(item) Remove an element from a set; it must be a member. If th


member, raise a KeyError.

13 symmetric_difference(....) Remove an element from a set; it must be a member. If th


member, raise a KeyError.

14 symmetric_difference_update(....) Update a set with the symmetric difference of itself and anoth

15 union(....) Return the union of sets as a


(i.e. all elements that are in either set.)

16 update() Update a set with the union of itself and others.

You might also like