Given one element in a list, what is the most efficient way that I can find the other elements?
(e.g. if a list is l=["A","B","C","D"]
and you're given "B", it outputs "A", "C" and "D")?
CodePudding user response:
Your question-: How do I find the other elements in a list given one of them?
Think like.. How can i remove that element in a list to get all other elements in a list [Quite simple to approach now!!]
Some methods are:-
def method1(test_list, item):
#List Comprehension
res = [i for i in test_list if i != item]
return res
def method2(test_list,item):
#Filter Function
res = list(filter((item).__ne__, test_list))
return res
def method3(test_list,item):
#Remove Function
c=test_list.count(item)
for i in range(c):
test_list.remove(item)
return test_list
print(method1(["A","B","C","D"],"B"))
print(method2(["A","B","C","D"],"B"))
print(method3(["A","B","C","D"],"B"))
Output:-
['A', 'C', 'D']
['A', 'C', 'D']
['A', 'C', 'D']
CodePudding user response:
There are few ways to achieve this, you want to find the other elements excluding the value. eg l1=[1,2,3,4,5] 2 to excluded l1=[1,3,4,5]
# a list
l1 =["a","b","C","d"]
#input of the value to exclude
jo = input()
l2=[]
for i in range(len(l1)):
if l1[i]!=jo:
l2.append(l1[i])
print(l2)