CBSE Class 12 Computer Science Question 56 of 56

Functions — Question 56

Back to all questions
56
Question

Question 49

Write a function LeftShift(lst, x) in Python which accepts numbers in a list (lst) and all the elements of the list should be shifted to left according to the value of x.

Sample Input Data of the list lst = [20, 40, 60, 30, 10, 50, 90, 80, 45, 29] where x = 3

Output lst = [30, 10, 50, 90, 80, 45, 29, 20, 40, 60]

Solution
def LeftShift(lst, x):
    if x >= len(lst):
        x %= len(lst)
    shifted_lst = lst[x:] + lst[:x]
    return shifted_lst

lst = eval(input("Enter the list: "))
x = int(input("Enter the value of x: "))
result = LeftShift(lst, x)
print(result)
Output
Enter the list: [20, 40, 60, 30, 10, 50, 90, 80, 45, 29]
Enter the value of x: 3
[30, 10, 50, 90, 80, 45, 29, 20, 40, 60]



Enter the list: [55, 66, 77, 88, 99, 44, 33, 22, 11]
Enter the value of x: 4
[99, 44, 33, 22, 11, 55, 66, 77, 88]
Answer

def
LeftShift
(
lst
,
x
):
if
x
>=
len
(
lst
):
x
%=
len
(
lst
)
shifted_lst
=
lst
[
x
:]
+
lst
[:
x
]
return
shifted_lst
lst
=
eval
(
input
(
"Enter the list: "
))
x
=
int
(
input
(
"Enter the value of x: "
))
result
=
LeftShift
(
lst
,
x
)
print
(
result
)
Output
Enter the list: [20, 40, 60, 30, 10, 50, 90, 80, 45, 29]
Enter the value of x: 3
[30, 10, 50, 90, 80, 45, 29, 20, 40, 60]

Enter the list: [55, 66, 77, 88, 99, 44, 33, 22, 11]
Enter the value of x: 4
[99, 44, 33, 22, 11, 55, 66, 77, 88]