Except | SoloLearn: Learn to code for FREE!

0

Except

Hi how can I say except in python for example names = [‘mr a’,’mr b’,’mr c’] Print(names) except ‘mr c’

7/13/2020 12:29:51 PM

Irsa

16 Answers

New Answer

+5

Irsa There are many ways to solve this problem Here I'm giving you 2 a=["mr a","mr b","mr c"] print(a[:-1]) #or a=["mr a","mr b","mr c"] b=[i for i in a if i!="mr c"] print(b) I hope it helped 🙂

+7

꧁༒Rishabh༒꧂ his question is unclear : - he wants maybe to remove the last element of the list (in that case you're right) - he wants to delete a specific element by comparing its value (in that case I'm right)

+6

+4

thanks every one 😀

+4

My interpretation suggests that Irsa is not seeking a way to handle exception but to leave out a specific element in a list. Interesting responses and views exhibited. What I can say is that, it depends on what you are comfortable with. - You can slice and leave the last item; - You can loop (for loop) through the list; - You can remove or delete the unwanted element and print the rest [:-1]; - You can check the element in the list and use continue (for loop) when the element is equal to 'mr c'; - You can use a lambda function and filter; Above all, it is crucial to consider writing a reusable code.

+3

names = ['mr a','mr b','mr c'] print(list(filter(lambda x: x!='mr c',names))) --- OUTPUT: ['mr a','mr b']

+3

+2

To include except you have to use try. But I didn't understood your concept.They are mostly used for handling errors. Please clarify it.. Then, I'll try to help you

+2

except keyword is used in exception handling : try: 1/0 except ZeroDivisionError as e: # handle the exception You want to print all objects in 'names' excepted 'mr c'. To achieve that, the easiest way at your level is creating a new list and display it. There are other ways to do this, using the built-in 'filter' function, for instance.

+2

Théophile If this is his question, then easiest way might be list slices..

+2

We can also get that result excluding 'mr.c' in this way.... print(names[0]) print(names[1])

+2

It's u can use the remove keyword for example friends = ["Batman","Pooboy"] friends.remove ("Pooboy") print (friends)

+1

You can use for loop to print all the elements you want, using if statement to exclude the ones you don't want

0

siddiraju Manaswi can be many name

0

0

Lucky Sibanda yeah is so the idea is it ,get out the element 'mr c' of the list