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]

>>> 


10 Comments

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

  1. Thanks for uploading answer .

    ReplyDelete
  2. Whenever I try it, it says tuple index out of range for a[i]. What to do?

    ReplyDelete
    Replies
    1. Please read the question again , you find that we have to enter a list not tuple ...

      Delete
  3. Hey Can we do this using list comprehension?

    ReplyDelete
    Replies
    1. Yes, Like this -

      newlist = [ x if x <= 10 else 10 for x in a ]
      print(newlist)

      Delete
  4. Replies
    1. Output are coming with both code. Please try again.

      Delete
  5. hi i am trying to use the code however it shows an error

    ReplyDelete
    Replies
    1. Please copy the code as it is then run it in your IDLE Python.

      Delete

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post