Operators
1 Arithmetic Operators
2 Comparison Operators
3 Assignment Operators
4 Bitwise Operators
5 Logical Operators
6 Membership Operators
Problem Statement(Arithmetic Operators):
Write a program to read two int inputs from the user and perform the
following arithmetic operations addition, subtraction, multiplication,
and division and print the result
Sample Input and Output:
num1: 10
num2: 5
Addition of 10 and 5= 15
Subtraction of 10 and 5 = 5
Multiplication of 10 and 5 = 50
Division of 10 and 5 = 2 0
Exponent of 10 with 5 = 100000
Modulus of 10 and 5 = 0
Floor Division of 10 and 5 = 2
Problem Statement (Comparison Operators):
Take two integers as input from the console using input () function For
each comparison operator (>, <, ==, !=, >=, <= ), print to the console,
the result of the two input numbers as shown in the example
Sample Input and Output:
num1: 20
num2: 10
Is 20 greater than 10 = True
Is 20 less than 10 = False
Is 20 equal to 10 = False
Is 20 not equal to 10 = True
Is 20 greater than or equal to 10 = True
Is 20 less than or equal to 10 = False
Problem Statement (Comparison Operators):
Write a program to understand the use of comparison operators using
conditional parameters Take input from user using input() method
Sample Input and Output
Is Rebecca greater than Bethany = True
Is Rebecca less than Bethany = False
Is Rebecca equal to Bethany = False
Is Rebecca not equal to Bethany = True
Is Rebecca greater than or equal to Bethany = True
Is Rebecca less than or equal to Bethany = False
Problem Statement (Assignment Operators):
Take two integers as input from the console using input() function For
each assignment operator (+=, -+, *=, /=, **=, //=, %=, =), print to the
console, the result of the two input numbers as shown in the example
Sample Input and Output:
x: 40
y: 30
x +=y: x = 70 and y = 30
x -= y: x = 10 and y = 30
x *= y: x = 1200 and y = 30
x /= y: x = 1 3333333333333333 and y = 30
x **= y: x =
1152921504606846976000000000000000000000000000000 and y = 30
x //= y: x = 1 and y = 30
x %= y: x = 10 and y = 30
x = y: x = 30 and y = 30
Note: Before every assignment operation, set the values of x and y to the
initially read values
Problem Statement (Bitwise Operators):
Take two integers x and y as inputs from the console
using input() function For each bitwise operator ( >> , <<, &, |, ~,
and ^ ), print to the console, the result of applying these operators
on the two input integers as shown in the example
Sample Input and Output:
x: 52
y: 20
52 >> 20 is 0
52 << 20 is 54525952
52 & 20 is 20
52 | 20 is 52
~ 52 is -53
52 ^ 20 is 32
Problem Statement (Logical Operators):
Write a program to understand the logical and operator Take
three integers as input from the user using input() function The
program should print True if a is 6 and b is 6 and c is not 6,
otherwise it should print False
Sample Input and Output 1:
a: 6
b: 6
c: 1
True
Sample Input and Output 2:
a: 2
b: 3
c: 5
False
Write a program to understand the logical or operator Take two
integers a and b as inputs from the console using input() function
The program should print True if either of the inputs is 6, their
sum is 6, or their difference is 6, Otherwise it should print False
Sample Input and Output1:
a: 59
b: 6
True
Sample Input and Output2:
a: 30
b: 30
False
The logical not operator negates the boolean operand given to it
E g not True is False Similarly, not(a and b) is the expression which
indicates True, only when both a and b are not True
Write a program to understand the logical not operator The
program should print Weekend if the day is either SAT or SUN,
otherwise it should print Not Weekend Take the input day from the
user
Sample Input and Output1:
Enter day: SAT
Weekend
Sample Input and Output2:
Enter day: MON
Not Weekend
Hint: Consider the days of the week are represented
as MON, TUE, WED, THU, FRI, SAT, SUN
Problem Statement (Membership Operators):
Take two strings as input from the console using input() function
Write a program using membership operators to check whether
the given second string is present in the first string or not Print
the result of the two input strings to the console, as shown in the
example
Sample Input and Output1:
str1: Hello World Welcome To Python Programming
str2: Pro
Pro in Hello World Welcome To Python Programming:
True
Sample Input and Output2:
str1: Regular Expression
str2: advanced
advanced in Regular Expression: False
Take two strings as input from the console using input() function
For each membership operator in and not in, print to the console,
the result of the two input strings as shown in the example
Sample Input and Output:
str1: Hello World
str2: worlds
worlds in Hello World is: False
worlds not in Hello World is: True
Let's write a simple program using the membership
operator in and not in
The below program has a predefined list Take an input element
from the user to check whether the given element is present in the
list or not Print the result as shown in the example
Sample Input and Output:
['A', '123', 'Ramana', [1, 2], 34 56, '55']
element: A
A in ['A', '123', 'Ramana', [1, 2], 34 56, '55'] is:
True
A not in ['A', '123', 'Ramana', [1, 2], 34 56, '55']
is: False
Problem Statement (Operators):
Write a program to read mass in kilograms (kg) which is in the
format of int Convert the mass entered in kilograms
into pounds(lb)
Hint: The formula for conversion is lb = 2 2 * kilograms
Sample Test Cases
Test case 1
kg:120
lb:264 0⏎
Test case 2
kg:36
lb:79 2⏎
Test case 3
kg:44
lb:96 80000000000001⏎
Write a program to read temperature in Celsius and print
the temperature in fahrenheit.
Hint: The formula for conversion is F = 1.8 *
Temperature_in_Celsius + 32.0.
Sample Test Cases
Test case 1
Temp in celsius: 23.30
Temp in Fahrenheit is 73.94⏎
Test case 2
Temp in celsius: 25.36
Temp in Fahrenheit is 77.648⏎
Problem Statement (if-else):
Write a program to check whether the given integer is divisible by
3 or not, and print the result to the console as shown in the
examples.
Sample Input and Output 1:
num: 66
divisible by 3
End of program
Sample Input and Output 2:
num: 52
End of program
Take an integer as input from the console using input() function.
Write a program to check whether the input amount is greater or
less than the minimum balance.
Follow the instructions while writing the program and print the
output as shown in the example.
Assume minimum balance is 1000
If input >= 1000 print Sufficient balance
Otherwise the message should print on the console as Balance is
Low
Sample Input and Output 1:
balance: 500
low
Sample Input and Output 2:
balance: 2000
sufficient
Write a program to check whether a number is positive or negative.
Take an integer, num, as an input from the console
using input() function and print the result to the console as shown
in the sample test case.
Sample Input and Output 1:
num: 02
positive
Sample Input and Output 2:
num: -52142
negative
Sample Input and Output 3:
num: 0
zero
Write a program to check whether a year is a leap year or not. Print
the result to the console as shown in the sample test cases.
Sample Input and Output 1:
year: 2004
leap year
Sample Input and Output 2:
year: 1700
not leap year
Problem Statement (While):
Take an integer num as input from the user. Write a code to find
the sum of all even numbers from 1 to num using while
construct, print the result to the console as shown in the example.
Sample Input and Output:
num: 100
sum: 2550
Hint:
sum = 2 + 4 + 8 + ....... + n (if n is even)
sum = 2 + 4 + 8 + ....... + n - 1 (if n is odd)
Sample Test Cases
Test case 1
num:12
sum:42⏎
Test case 2
num:0
sum:0⏎
Test case 3
num:2010
sum:1011030⏎
Take an integer num as input from the console
using input() function. Write a program to find the sum of all
integers between 0 and num, both inclusive. Print the result to
the console as shown in the examples.
Sample Input and Output 1:
num: 250
sum: 31375
Sample Input and Output 2:
num: -660
sum: -218130
Take an integer x as an input from the console
using input() function. Write a program that calculates
the Fibonacci series upto x-1, and also calculates the sum of all
even-indexed numbers in the generated list. Print the result to the
console as shown in the example.
Sample Input and Output 1:
k: 25
0
1
1
2
3
5
8
13
21
sum: 33
Explanation: Starting index of first digit is 0, So the sum of even-
numbered digits is 0 + 1 + 3 + 8 + 21 = 33
Generate a sequence of k integers starting from 0.And for each
number, determine whether it is even or odd.
Print the result to the console as shown in sample test case.
Sample input and output:
k: 5
0 even number
1 odd number
2 even number
3 odd number
4 even number
Write a program to create a Dictionary with the input capital and
corresponding state. And the program should terminate once the
user enters end.
Print the result as shown in the below example.
Sample Input and Output:
state or 'end' to quit: Andra Pradesh
capital: Amaravathi
state: end
[('Andra Pradesh', 'Amaravathi')]
Note: Whenever you print the dictionary (as a whole),
please use sorted(dict.items()) so that the items get
printed in sorted order (not in random order),
otherwise the test cases will fail. The return type
of sorted function will be tuples (key,value) rather
than key, value pairs separated by :
Test case 3
state·or·'end'·to·quit:·end
[]⏎
Problem Statement (for):
Write a program that finds the factors of a number n and checks
whether the given number is a perfect number or not. Print the
result to the console as shown in the examples.
Sample Input and Output 1:
n: 6
factors: [1, 2, 3]
perfect number
Sample Input and Output 2:
n: 32
factors: [1, 2, 4, 8, 16]
not perfect number
Hint: A number is called a perfect number if the sum of all its
factors (excluding itself) is equal to the number
Write a program that prints the value of Pi up to n decimals. Print
the result as shown in the example.
Sample Input and Output:
n: 5
3.1
3.14
3.142
3.1416
3.14159
Program to check the depth and correctness of parenthesis
Write a program that checks for matching parenthesis, and prints
an error if they do not match. Print the depth (nesting level) if they
match as shown in the examples.
Sample Input and Output 1:
str: (())
valid and depth: 2
Sample Input and Output 2:
str: ()))
not valid and errors: 2
Take a character input from the user using input() function. Write
a program to check whether the given input is a vowel or not.
Print the result to the console as shown in the examples.
Follow the below constraints while writing the program.
If the input is an alphabet, then the program should ask the user
to enter the input again.
If the input is a digit other than 9, the program should print wrong
input.
If the input is 9, the program should exit.
Sample Input and Output 1:
vowel, or 9 to quit: a
vowel
vowel, or 9 to quit: w
not vowel
vowel, or 9 to quit: 5
wrong input
vowel, or 9 to quit: 9
Sample Input and Output 2:
vowel, or 9 to quit: o
vowel
vowel, or 9 to quit: O
vowel
vowel, or 9 to quit: 9
Practice Programs - Control Statements
Write a program to calculate the Fibonacci series i.e., 0 1 1 2 3 5
8 13 21....., up to the given limit n, print the result to the console
as shown in the example.
Sample Input and Output:
n: 5
0
1
1
2
3
5
Hint: By definition, the first two numbers in
the Fibonacci sequence are 0 and 1, and each subsequent
number is the sum of previous two.
Sample Test Cases
Test case 1
n:·0
0⏎
Test case 2
n:·5
0⏎
1⏎
1⏎
2⏎
3⏎
5⏎
Test case 3
n:·4
0⏎
1⏎
1⏎
2⏎
3⏎
Take two integers x and y as input from the console,
consider x as lower limit and y as upper limit. Write a program to
find all the prime numbers between x and y
Sample Input and Output:
x: 10
y: 30
11
13
17
19
23
29
Hint: A prime number is a positive integer greater than 1 and is
divisible by 1 and itself only. A few prime numbers are 2, 3, 5, 7,
11, 13, 17, 19, etc.
An Armstrong Number is a number that is equal to the sum of its
own digits each raised to the power of the number of digits.
Example:
153 = 1 ^ 3 + 5 ^ 3 + 3 ^ 3 = 1 + 125 + 27 = 153 # Armstrong
Number
1634 = 1 ^ 4 + 6 ^ 4 + 3 ^ 4 + 4 ^ 4 = 1634 # Armstrong Number
Take an integer as input from the console. Write a program to find
whether the given integer is an Armstrong number or not, and
print the result to the console as shown in the examples.
Sample Input and Output 1:
n: 1634
sum of powers: 1634
armstrong number
Sample Input and Output 2:
n: 123
sum of powers: 36
not armstrong number
Take character as input from the console using input() function.
Write a program to check whether the given input is a vowel or
a consonant or a letter are not. Print the result to the console as
shown in the examples.
Sample Input and Output 1:
ch: A
letter and vowel
Sample Input and Output 2:
ch: P
letter and consonant
Sample Input and Output 3:
ch: @
not letter
Take three integers a, b and c as inputs. Write a program to find
the largest of the given three inputs and print the result to the
console as shown in the examples.
Sample Input and Output:
a,b,c: 120,45,632
632
Note: use split() function to separate user given data based on ','.
Write a program to print the Floyd's Triangle of n rows. Print the
result to the console as shown in the example.
Sample Input and Output:
n: 5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Note: Floyd's triangle is a right-angled triangular array of natural
numbers, used in computer science education. It is defined by
filling the rows of the triangle with consecutive numbers, starting
with 1 in the top left corner.
Strings
lang = "Python"
Print(a[0:4])
Print(a[ :3])
Print(a[0: ])
print (a[::1])
print(a[::-1])
print(a[-1::-3])
print(a[4:1:-1])
print(a[2:5:-1])
String is How are you?
# print 'are' in String using Slicing with Positive
Index
Are
# print 'w a' in String using Slicing with Positive
Index
w a
# print 'you' in String using Slicing with Negative
Index
You
# print 'uoy' in the string using slicing and
Negative indexes and negative step
uoy
# print 'you?' in String using Slicing with Negative
Index
you?
Write a program to take a string as input from the user. Print first
and last two characters of a string. If the length of the string is
less than 3 then print the input string as it is.
Print the result as shown in the sample test case.
Sample Input and Output 1:
input: Code Tantra
output: Cora
Sample Input and Output 2:
input: hi
output: hi
Write a program to take string as input from the user
using input() function. Remove first and last characters of given
string.
Print the result as shown in the sample test case.
Sample Input and Output:
str: Python
output: ytho
Write a program to take a string as input from the user. Swap the
first and last characters of the given string. Print the resultant
string as shown in the sample test case.
Follow the below constraints while writing the program:
If length of the string is 1 then print the input string as it is.
If length of the string is 0 (zero) then print null as output.
Sample Input and Output 1:
str: Active
output: ectivA
Sample Input and Output 2:
str: T
T
Write a program that takes two input strings str1 and str2 and
returns the result by concatenating them in the
order str1str2str2str1.
Print the result as shown in the sample test case.
Sample Input and Output:
str1: Code
str2: Tantra
result: CodeTantraTantraCode
Write a program to remove a character from a string based on
integer value given by the user. Treat the input as an index of a
string.
Print the result as shown in the sample test cases.
Sample Input and Output 1:
str: Python Programming
num: 9
Python Prgramming
Sample Input and Output 2:
str: Strings
num: 10
num should be positive, less than the length of str
Write a program to take a string as input from the user. If the
length of given string is greater than or equal to 3 then print first
three characters 3 times. If not print the string as it is.
Print the result as shown in the sample test cases.
Sample Input and Output 1:
str: Python
result: PytPytPyt
Sample Input and Output 2:
str: Hi
result: Hi
Given an input string a = "hello python", now understand the
working principles of the following methods:
1) capitalize() - Capitalizes first letter of a string.
print(a.capitalize()) # Result: Hello python
2) upper() - Converts the string to uppercase.
print(a.upper()) # Result: 'HELLO PYTHON'
3) lower() - Converts the string to uppercase.
print(a.lower()) # Result: 'hello python'
4) title() - Converts the string to title case. i.e., first characters of
all the words of string are capitalized.
print(a.title()) # Result: 'Hello Python'
5) swapcase() - Swap the case of characters. i.e., lowercase into
uppercase and vice versa.
print(a.swapcase()) # Result: 'HELLO PYTHON'
6) split() function returns a list of words separated by space.
print(a.split()) # Result: ['hello',
'python']
7) center(width,"fillchar") Center the string within a
specified width using a fill character. Observe the below
example:
print(a.center(20, '*')) # Result: '****hello
python****'
Here, width is 20 and string length is 12, so now we need to fill the
remaining width(20 - 12 = 8) with '*' special character.
8) count() returns the number of occurrences of substring in
particular string. If the substring does not exist, it returns zero.
a = "happy married life happy birthday birthday"
print(a.count('happy')) # Result: 2 (happy word
occurred two times in a string)
print(a.count('birthday')) # Result: 2
print(a.count('life')) # Result: 1
9) replace(old, new), this method replaces all old substrings with
new substrings. If the old substring does not exist, no
modifications are done.
a = "java is simple"
print(a.replace('java' ,'Python')) # Result:
'Python is simple'
Here java word is replaced with Python.
10) join() returns a string concatenated with the elements of an
iterable. (Here “L1” is iterable)
b = '.'
L1 = ["www", "codetantra", "com"]
print(b.join(L1)) # Result: 'www.codetantra.com'
Here '.' symbol is concatenated/joined with every item of the list.
11) isupper() - Checks if all characters in the string are
uppercase or not. If yes returns True, otherwise False.
12) islower() - Checks if all characters in the string are lowercase
or not. If yes returns True, otherwise False.
13) isalpha() - Checks if the string contains alphabetic characters
only or not. If yes returns True, otherwise False.
Space is not considered as alphabet character, it will fall in the
category of special characters.
14) isalnum() - Checks if the string contains alphanumeric
characters only or not. If yes returns True, otherwise False.
Characters those are not alphanumeric are: (space) ! # % & ? etc.
Numerals (0-9), alphabets (A-Z, a-z) will fall into the category of
alphanumeric characters.
Now, let's understand these methods with small example.
Assume there is an string a = "HELLOWORLD123". Observe the
output:
print(a.isupper()) # Result: True
print(a.islower()) # Result: False
print(a.isalpha()) # Result: False
print(a.isalnum()) # Result: True
15) isdigit() is used to check whether a string consists of digits
only or not. If the string contains only digits then it returns True,
otherwise False.
a = "123"
print(a.isdigit()) # will print result as follows
True
Here the string 'a' contains only digits so it
returns True.
a = "123hello"
print(a.isdigit()) # will print result as follows
False
16) isspace() checks whether a string consists of spaces only or
not. If it contains only white spaces then it
returns True otherwise False.
a = " "
18) startswith(substring) checks whether the main string starts
with given sub string. If yes it returns True, otherwise False.
a = "hello python"
print(a.startswith('h')) # will print result as
follows
True
19) endswith(substring) checks whether the string ends with the
substring or not.
a = "hello python"
print(a.endswith('n')) # will print result as follows
True
20) find(substring) returns the index of the first occurrence of the
substring, if it is found, otherwise it returns -1
a = "hello python"
print(a.find('py')) # will print result as follows
6
a = "hello python"
print(a.find('java')) # will print result as follows
-1
21) len(a) returns the length of the string.
a = 'hello python'
print(len(a)) # will print result as follows
12
22) min(a) returns the minimum character in the string
a = "Hello Python"
print(min(a)) # will print result as follows
# min(a) prints space because space is minimum value
in Hello Python.
Here it returns white space because in the given string white
space is the minimum of all characters.
23) max(a) returns the maximum character in the string.
print(max(a)) # will print result as follows
y
Write a program to print every character of the given input string
twice.
Print the result to the console as shown in the sample test case.
Sample Input and Output:
str: Lists
result: LLiissttss
Write a program to calculate length of the string, If length
is even print first half of the string, if the length is odd remove the
middle character.
Print the second half of the string as shown in sample test case.
Sample Input and Output 1:
str: Python
first half str of even length: Pyt
Sample Input and Output 2:
str: Hello World
second half str of odd length: World
Write a program to divide the string into two substrings by taking
the alternate characters and print both the strings. Again from
these two substrings, make the original string.
If length is zero then, the program should print 'null'
If the length is 1 then, the program should print the message on
the console as shown in the sample test case 3.
Print the result as shown in the sample test cases.
Sample Input and Output 1:
str: Python
first: Pto
second: yhn
original: Python
Sample Input and Output 2:
str:
null
first:
second:
original:
Sample Input and Output 3:
str: H
H
first: H
second:
original: H
Take string as input from the console using input() function. Write
a program to find how many times each character is repeated in a
given string. Print each character in the string in sorted order with
a number of times it is repeated as shown in the example.
Sample Input and Output:
str: Hello Python!
' ' 1
'!' 1
'H' 1
'P' 1
'e' 1
'h' 1
'l' 2
'n' 1
'o' 2
't' 1
'y' 1
[' ', '!', 'H', 'P', 'e', 'h', 'l', 'n', 'o', 't',
'y']
Write a program to find how many times a single digit is repeated
in a given number, and print the result as shown in the example.
Sample Input and Output:
str: 11454
1 2
4 2
5 1
Note: The output should be printed in the order of the
appearance of digits in the given number.
List
Operations Example Description
a = [2 ,3, 4, 5, 6,
7, 8, 9, 10] Create a comma
separated list of
Create a List print(a) # [2 ,3,
elements and assign to
4, 5, 6, 7, 8, 9,
variable 'a'
10]
Access the item at
position '0'
print(a[0]) # 2
Indexing Access the last item
print(a[-1]) # 10
using negative
indexing
print(a[0:3]) # [2, Print a part of list
3, 4] starting at index '0' till
index '2'
Slicing print(a[0:]) # [2,
Print a part of the list
3, 4, 5, 6, 7, 8,
starting at index '0' till
9, 10]
the end of list
b = [20, 30]
print(a + b) # [2, Concatenate two lists
Concatenation
3, 4, 5, 6, 7, 8, and display its output
9, 10, 20, 30]
a[2] = 100
print(a) # [2, 3, Update the list element
Updating
100, 5, 6, 7, 8, 9, at index 2
10]
Membership 5 in a # True Returns True if
102 in a # False element is present in
list.
Otherwise returns
Operations Example Description
false.
a = [2, 3, 4, 5, 6, Returns True if all
elements in both lists
7, 8, 9, 10]
Comparison are same.
b = [2, 3, 4]
a == b # False
Otherwise returns false
a = [1, 2, 3]
Here the * operator
print(a * 3) # [1,
Repetition repeats a list for the
2, 3, 1, 2, 3, 1,
given number of times.
2, 3]
Create a list by taking input from the user for its elements. Write a
program to find the first and last elements in the list.
Print the result as shown in the sample test case.
Sample Input and Output 1:
data: Godavari,Krishna,Kaveri
first, last elements: Godavari Kaveri
Sample Input and Output 2:
data: 10,20,30,45,56
first, last elements: 10 56
Slices Example Description
a = [9, 8, 7, 6, 5,
4]
a[0:3] Print a part of list from index 0 to 2
a[0:3]
[9, 8, 7]
Slices Example Description
a[:4] Default start value is 0.
a[:4]
[9, 8, 7, 6] Prints the values from index 0 to 3
a[1:]
a[1:] Prints values from index 1 onwards
[8, 7, 6, 5, 4]
a[:]
a[:] Prints the entire list
[9, 8, 7, 6, 5, 4]
a[2:2]
a[2:2] Prints an empty slice
[]
a[0:6:2]
a[0:6:2] Slicing list values with step size 2
[9, 7, 5]
a[::-1]
a[::-1] Prints the list in reverse order
[4, 5, 6, 7, 8, 9]
a[-3:]
a[-3:] Prints the last 3 items in list
[6, 5, 4]
a[:-3] Prints all except the last 3 items in
a[:-3]
[9, 8, 7] list
a = [9, 8, 7, 6, 5, 4]
a[0:3]
a[:4]
a[:]
a[2:2]
a[0:6:2]
a[-3:]
a[:-3]
Create a list of integers by taking the input from the user. Write a
program to print True if the first or last element of the List is 3,
otherwise print False.
Sample Input and Output 1:
data: 12,52,63,96,85,3
True
Sample Input and Output 2:
data: 11,22,33,44,55,66,3,77
False
extend() method
x.extend(y)
Write a program that takes input for two comma-separated lists,
along with a number. The program should repeat and print each
list the specified number of times and then combine the lists and
display the final merged list as shown in the sample test cases.
Sample Input and Output 1:
data1: Python,Java
data2: Perl,Swift
num: 2
['Python', 'Java', 'Python', 'Java']
['Perl', 'Swift', 'Perl', 'Swift']
extending list1 with list2: ['Python', 'Java',
'Perl', 'Swift']
Example Description
a = [1, 2, 3, 4, 5]
a[0] = 100
Changing a single element
print(a) # Output:
[100, 2, 3, 4, 5]
Example Description
a = [1, 2, 3, 4, 5]
a[0:3] = [100, 100, 100]
Changing multiple elements
print(a) # Output:
[100, 100, 100, 4, 5]
a = [1, 2, 3, 4, 5] Certain elements from a list can
a[0:3] = [ ] also be
print(a) # Output: [4, removed by assigning an empty
5] list to them
a = [1, 2, 3, 4, 5] The elements can be inserted
a[0:0] = [20, 30, 45] into a list by
print(a) # Output: [20, squeezing them into an empty
30, 45, 1, 2, 3, 4, 5] slice at the desired location
Create a list with the user-given inputs. Take an index
value n from the user. Write a program to update a list with user
given element based on index n, if the index is not in the range,
print the error message as shown in the sample test cases.
Sample Input and Output 1:
data: James,John,Jacob
before updation: ['James', 'John', 'Jacob']
index: -2
element: Oliver
after updation: ['James', 'Oliver', 'Jacob']
Sample Input and Output 2:
data: 10,20,54,26
before updation: ['10', '20', '54', '26']
index: 4
invalid
Create an integer list with the user-given inputs. Compare the first
and last elements in the list. Print the largest one as shown in the
sample test case.
Sample Input and Output:
data: 48,96,55,63,255,96,800
[48, 96, 55, 63, 255, 96, 800]
largest among first, last elements: 800
Create two lists with the user-given elements. Write a program to
check whether the first or last elements of two lists are the same
or not. If yes print True, otherwise print False as shown in the
examples.
Sample Input and Output 1:
data1: Python,Java,Perl,Swift
data2: Django,Flask,Swift
True
Sample Input and Output 2:
data1: 10,20,30,40
data2: 50,60,30,40,20
False
Deleting or removing elements from a list
One or more elements of a list can be deleted using the
keyword del. This can as well delete the entire list.
dlist = ['red', 'orange', 'blue', 'green', 'yellow',
'red']
print(dlist)
['red', 'orange', 'blue', 'green', 'yellow', 'red']
del dlist[5]
print(dlist)
['red', 'orange', 'blue', 'green', 'yellow']
del dlist[2:]
print(dlist)
['red', 'orange']
del dlist
The list remove(element) method is also used for this purpose.
This method searches for the given element in the list and
removes the first matching element.
remlist = ['red', 'orange', 'blue', 'green',
'yellow', 'red']
remlist.remove('green')
print(remlist)
['red', 'orange', 'blue', 'yellow', 'red']
The pop(index) method removes and returns the item at index, if
index is provided.
If index is not provided as an argument, then pop() method
removes and returns the last element.
plist = ['red', 'orange', 'blue', 'green', 'yellow',
'cyan']
elem = plist.pop()
print(elem)
'cyan'
elem = plist.pop(-1)
print(elem)
'yellow'
print(plist)
['red', 'orange', 'blue', 'green']
The clear() method is to used to clear the contents of a list and
make it empty.
plist.clear()
print(plist)
[]
Create a list with the user-given input elements. Write a program
to remove all the duplicate elements from the given input list.
Print the result as shown in the sample test case.
Sample Input and Output:
data: 10,20,10,30
['10', '20', '10', '30']
after removing duplicates: ['10', '20', '30']
mylist = list(dict.fromkeys(mylist))
Here is a list of built-in functions that can be applied on a list:
1. all(): Returns True if all the items in the list have a true value.
print(all([' ', ',', '1', '2']))
True
2. any(): Returns True if atleast one item in the list has a true
value.
print(any([' ', ',', '1', '2']))
True
3. enumerate(): Returns an enumerate object consisting of the
index and the values of all items of the list as a tuple pair.
print(list(enumerate(['a','b','c','d','e'])))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]
4. len(): It calculates the length of the list i.e., the number of
elements in the list.
print(len(['a', 'b', 'c', 'd', 'e']))
5
5. max(): Returns the item with the highest value from the list
print(max([1, 2, 3, 4, 5]))
5
6. min(): Returns the item with the lowest value from the list.
print(min([1, 2, 3, 4, 5]))
1
7. sorted(): Returns a sorted version of the given list, leaving the
original list unchanged.
origlist = [1, 5, 3, 4, 7, 9, 1, 27]
print(sorted(origlist)
[1, 1, 3, 4, 5, 7, 9, 27]
8. sum(): Returns the sum of all the elements of a list. It works
only on an integer list.
print(sum([1, 5, 3, 4, 7, 9, 1, 27]))
57
Write a program to find the difference between the maximum
and the minimum elements of a list and print the result as shown
in the example.
Sample Input and Output:
data: 12,52,96,85
min: 12
max: 96
difference: 84
Write a program to find the sum of elements of the given
integer list and print the result as shown in the example.
Sample Input and Output:
data: 10,20,30,40,50,60,70,80,90,100
sum: 550
Write a program to find the sum of the elements, square of
each element, and the sum of squares of elements of a list,
and print the result as shown in the example
Use a list and its functions to get the desired result.
Sample Input and Output:
data: 10,20,30
list: [10, 20, 30]
sum: 60
squares: [100, 400, 900]
sum of squares: 1400