I am using the filter function for the first time and using a function to remove del_num from a tuple called num_list. However, it's not doing what I want. I am getting back the original num_list values. Appreciate any ideas on how to get this to work.
num_list = [1,2,3,4,5,8,24,24,54,78]
del_num = 24
def filter_list(num_list, del_num):
new_num =[]
for v in num_list:
if (num_list) == (del_num):
return FALSE
else:
new_num.append(v)
return new_num
result = filter_list(num_list,del_num)
print(result)
One way to do this is using list comprehension
num_list = [1,2,3,4,5,8,24,24,54,78]
del_num = 24
def filter_list(num_list,del_num):
return [num for num in num_list if num != del_num]
filtered_list = filter_list(num_list,del_num)
print(filtered_list)
Making minimal changes to the overall structure of your code, but making some changes so it works:
num_list = [1,2,3,4,5,8,24,24,54,78]
del_num = 24
def filter_list(num_list, del_num):
new_num = []
for v in num_list:
if v != del_num:
new_num.append(v)
return new_num
result = filter_list(num_list,del_num)
print(result)
The return False
portion of your code will break out of the function and return False
if the condition is met, which is not what you want. Additionally, the equality check you were doing was comparing the original list to the number to be deleted. You should have done if v == del_num
. Given that all the action happens in the else
block, easiest to turn the equality into an inequality and get rid of the else
block entirely.
Also note that the boolean False is spelt False
, not FALSE
(unlike some other languages).
Here is what are you looking for:
num_list = [1,2,3,4,5,8,24,24,54,78]
del_num = 24
def filter_list(num_list, del_num):
new_num =[]
for v in num_list:
if (v) == (del_num):
pass
else:
new_num.append(v)
return new_num
result = filter_list(num_list,del_num)
print(result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.