Q. Ask the user to enter a list containing numbers between 1 and 12 then replace all of the entries in the list that are greater than 10 with 10.
You can understand by Watching video :-
Answer :-
a = eval(input ("Enter the list =")) for i in range(len(a)) : if a[i] > 10 : a[i] = 10 print ("New list ",a)
OR
By List Comprehension Method
a = eval(input ("Enter the list =")) newlist = [ x if x <= 10 else 10 for x in a ] print("New list ",newlist)
Output :-
Enter the list =[9,12,15,2,3,18]
New list [9, 10, 10, 2, 3, 10]
>>>
Enter the list =[78,5,2,98,41,35,2,8,1,10]
New list [10, 5, 2, 10, 10, 10, 2, 8, 1, 10]
>>>
Thanks for uploading answer .
ReplyDeleteWelcome : )
DeleteWhenever I try it, it says tuple index out of range for a[i]. What to do?
ReplyDeletePlease read the question again , you find that we have to enter a list not tuple ...
DeleteHey Can we do this using list comprehension?
ReplyDeleteYes, Like this -
Deletenewlist = [ x if x <= 10 else 10 for x in a ]
print(newlist)
why first coding not working
ReplyDeleteOutput are coming with both code. Please try again.
Deletehi i am trying to use the code however it shows an error
ReplyDeletePlease copy the code as it is then run it in your IDLE Python.
DeletePost a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )