Except | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Except

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

13th Jul 2020, 12:29 PM
Irsa
Irsa - avatar
13 Answers
+ 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)
13th Jul 2020, 12:47 PM
Théophile
Théophile - avatar
+ 4
thanks every one 😀
13th Jul 2020, 2:37 PM
Irsa
Irsa - avatar
+ 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.
14th Jul 2020, 11:18 PM
Lucky Sibanda
Lucky Sibanda - avatar
+ 3
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
13th Jul 2020, 12:35 PM
Arctic Fox
Arctic Fox - avatar
+ 3
Théophile If this is his question, then easiest way might be list slices..
13th Jul 2020, 12:39 PM
Arctic Fox
Arctic Fox - avatar
+ 3
names = ['mr a','mr b','mr c'] print(list(filter(lambda x: x!='mr c',names))) --- OUTPUT: ['mr a','mr b']
13th Jul 2020, 2:13 PM
Suhail KM
+ 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.
13th Jul 2020, 12:37 PM
Théophile
Théophile - avatar
+ 2
We can also get that result excluding 'mr.c' in this way.... print(names[0]) print(names[1])
13th Jul 2020, 5:48 PM
Siddiraju Manaswi
Siddiraju Manaswi - avatar
+ 2
It's u can use the remove keyword for example friends = ["Batman","Pooboy"] friends.remove ("Pooboy") print (friends)
14th Jul 2020, 10:28 AM
🔥 Destiny Travolta 🔥
+ 1
You can use for loop to print all the elements you want, using if statement to exclude the ones you don't want
13th Jul 2020, 12:41 PM
Justus
Justus - avatar
0
siddiraju Manaswi can be many name
13th Jul 2020, 5:54 PM
Irsa
Irsa - avatar
0
heit
14th Jul 2020, 7:47 AM
HALAI JAYESHKUMAR
HALAI JAYESHKUMAR - avatar
0
Lucky Sibanda yeah is so the idea is it ,get out the element 'mr c' of the list
14th Jul 2020, 11:48 PM
Richar Lopez
Richar Lopez - avatar