Home > Software engineering >  How get only the values from list comprehension in a python function?
How get only the values from list comprehension in a python function?

Time:05-18

Here is a list, n_list

n_list = [2, 4, 4, 5, 2, 1, 7, 1, 9]

Problem Statement:

I would like to get the result from list comprehension but the output should just be the value, not the list. Basically, result without writing a separate for loop for it.

Simple Solution but not what I want:

If I had to only print the result, I can do this way, using *:

print(*[val for val in n_list if n_list.count(val) == 1])

Current Issue:

However, while applying it to a function, I am getting error:

def singleVal(n_list):
    return(*[val for val in n_list if n_list.count(val) ==1])
    
singleVal(n_list)

Error: Can’t use started expression here.

Is there any way to get only the values from list comprehension in a function?

Expected Output:

Ultimately, should be something like the following code but in a function form and using list comprehension method:

result = [val for val in a if a.count(val) ==1]
    for i in result:
       return I

Return:

int: the element that occurs only once

CodePudding user response:

The simplest thing to do here is to return the list, and then use the * operator to print it:

def singleVal(n_list):
    return [val for val in n_list if n_list.count(val) == 1]
    
print(*singleVal([2, 4, 4, 5, 2]))  
# 5

If you are very certain that there will be exactly one value to return, you can write your function to just return that one value, e.g.:

def singleVal(n_list):
    return next(val for val in n_list if n_list.count(val) == 1)
    
print(singleVal([2, 4, 4, 5, 2]))  
# 5

Note that the above version of singleVal will only return the first unique value if there is more than one unique value in n_list, and will raise StopIteration if there are zero unique values.

If you want your function to return the list in the form of a single string, you can use join:

def singleVal(n_list):
    return " ".join(str(val) for val in n_list if n_list.count(val) == 1)
    
print(singleVal([2, 4, 4, 5, 2]))  
# 5

Note that converting the result to a string makes it easy to print, but very difficult to do anything else with (you'd need to use split() and int() to convert it back to a list of numeric values).

CodePudding user response:

def singleVal(L):
    result = [str(val) for val in L if L.count(val)==1]
    return '\n'.join(result)
  • Related