Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A quick way to return list without a specific element in Python

Tags:

python

If I have a list of card suits in arbitrary order like so:

suits = ["h", "c", "d", "s"] 

and I want to return a list without the 'c'

noclubs = ["h", "d", "s"] 

is there a simple way to do this?

like image 268
fox Avatar asked Apr 01 '13 06:04

fox


People also ask

How do you return a list without the first element in Python?

Use list. pop() to remove the first element from a list. Call list. pop(index) on a list with index as 0 to remove and return the first element.

How do you exclude an element from a list in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.

How do I remove one occurrence from a list in Python?

The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.


2 Answers

suits = ["h","c", "d", "s"]  noclubs = [x for x in suits if x != "c"] 
like image 110
avasal Avatar answered Sep 29 '22 02:09

avasal


>>> suits = ["h","c", "d", "s"] >>> noclubs = list(suits) >>> noclubs.remove("c") >>> noclubs ['h', 'd', 's'] 

If you don't need a seperate noclubs

>>> suits = ["h","c", "d", "s"] >>> suits.remove("c") 
like image 27
jamylak Avatar answered Sep 29 '22 00:09

jamylak