Python statement
Python statement
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.
1. if expression:
2. statement
Example 1
Output:
Output:
Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest
ADVERTISEMENT
ADVERTISEMENT
If the condition is true, then the if-block is executed. Otherwise, the else-block is
executed.
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.
Output:
Output:
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
Output:
Example 2
Output:
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.
2 For loop This type of loop executes a code block multiple times and abbreviates the
the loop variable.
ADVERTISEMENT
ADVERTISEMENT
Python provides the following control statements. We will discuss them later in detail.
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.
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
Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
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.
Code
Output:
ADVERTISEMENT
ADVERTISEMENT
P
y
t
h
If block
n
L
If block
If block
p
Syntax:
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
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.
Code
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
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.
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
Output:
Python Loops
Python Loops
Python Loops
Python Loops
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
Code
Continue Statement
It returns the control to the beginning of the loop.
ADVERTISEMENT
ADVERTISEMENT
Code
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
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
Output:
Last Letter: s
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.
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:
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]
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 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.
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:
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
If we don't know how many times we'll execute the iteration ahead of time, we can write
an indefinite 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
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 -
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
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).
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 -
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
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
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 -
Now we give code examples of while loops in Python for square every number of a list.
The code is given below -
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
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 -
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 -
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)
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
Continue Statement
It returns the control of the Python interpreter to the beginning of the loop.
Code
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
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
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
Output:
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;
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.
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.
Output:
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.
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.
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
Code
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.
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.
Code
Output:
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.
Interpretation It's mostly utilized within a loop's condition. During the byte-comp
keyword is removed.
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
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.
Code
Output:
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.
Syntax:
Here, if we check the type of the variable str using a Python script
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.
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
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.
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.
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.
Example 1
1. str = "HELLO"
2. str[0] = "h"
3. print(str)
Output:
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
1. str = "JAVATPOINT"
2. del str[1]
Output:
1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)
Output:
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 range slice operator. It is used to access the characters from the specified ra
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
Example
Consider the following example to understand the real use of Python operators.
Output:
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 -
Output:
2. \\ Backslash print("\\")
Output:
\
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
Output:
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:
Method Description
decode(encoding = 'UTF8', errors Decodes the string using codec registered for
= 'strict') encoding.
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.
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:
Characteristics of Lists
The characteristics of the List are as follows:
ADVERTISEMENT
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
Code
Output:
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)
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.
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]
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
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.
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]
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
Output:
3. Length
It is used to get the length of the list
Code
Output:
4. Iteration
The for loop is used to iterate over the list elements.
Code
Output:
12
14
16
39
40
5. Membership
It returns true if a particular item exists in a particular list otherwise false.
Code
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
Consider the accompanying model, where we take the components of the rundown
from the client and print the rundown on the control center.
Code
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
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:
1. len()
2. max()
3. min()
len( )
It is used to calculate the length of the list.
Code
Output:
Max( )
It returns the maximum element of the list
Code
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
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:
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]:
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:
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
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
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
Output:
Essentially adding a bracket around the component is lacking. A comma must separate
the element to be recognized as a tuple.
Code
Output:
<class 'str'>
<class 'tuple'>
<class 'tuple'>
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.
The method by which elements can be accessed through nested tuples can be seen in
the example below.
Code
Output:
Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6
o Negative Indexing
ADVERTISEMENT
The last thing of the assortment is addressed by - 1, the second last thing by - 2, etc.
Code
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
Output:
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.
Output:
ADVERTISEMENT
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.
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
Code
True
False
False
True
Code
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.
Code
ADVERTISEMENT
Output:
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.
Code
Output:
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.
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
Output:
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.
Output:
<class 'set'>
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.
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:
In the above code, we can see that set5 consisted of multiple duplicate elements when
we printed it remove the duplicity from the set.
Output:
To add more than one item in the set, Python provides the update() method. It accepts
iterable as an argument.
ADVERTISEMENT
Output:
ADVERTISEMENT
Output:
Python provides also the remove() method to remove the item from the set. Consider
the following example to remove the items using remove() method.
Output:
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.
Output:
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
Output:
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.
Example-
Output:
ADVERTISEMENT
Output:
Python also provides the union() method which can also be used to calculate the union
of two sets. Consider the following example.
ADVERTISEMENT
1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1.union(Days2)) #printing the union of the sets
Output:
Program:
Output:
{1, 2, 3, 4, 5}
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.
Output:
{'Monday', 'Tuesday'}
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
Output:
{3}
ADVERTISEMENT
Output:
{'castle'}
Output:
{'Thursday', 'Wednesday'}
Output:
{'Thursday', 'Wednesday'}
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}
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.
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).
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.
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'>
Output:
<class 'dict'>
<class 'frozenset'>
Name
Country
ID
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:
1. set1 = set([1,2,4,"John","CS"])
2. set1.update(["Apple","Mango","Grapes"])
3. print(set1)
Output:
Output:
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}
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:
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
SN Method Description
1 add(item) It adds an item to the set. It has no effect if the item is already
4 difference_update(....) It modifies this set by removing all the items that are also pres
sets.
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).
11 pop() Remove and return an arbitrary set element that is the last
Raises KeyError if the set is empty.
14 symmetric_difference_update(....) Update a set with the symmetric difference of itself and anoth