How to set local variable in list comprehension?

python local variable in list comprehension
python list comprehension variable not defined
list comprehension || python
python use variable in list comprehension
python list comprehension scope
python list comprehension multiple variables
pdb list comprehension
python list comprehension not defined

I have a method that takes a list and returns an object:

# input a list, returns an object
def map_to_obj(lst):
    a_list = f(lst)
    return a_list[0] if a_list else None

I want to get a list that contains all the mapped elements that aren't None.

Like this:

v_list = [v1, v2, v3, v4]

[map_to_obj(v) for v in v_list if map_to_obj(v)]

But it doesn't seem good to call the map_to_obj method twice in the list comprehension.

Is there a way to have local variables in list comprehensions so that it can have better performance?

Or does the compiler optimize it automatically?

Here is what I want:

(sml like)
[let mapped = map_to_obj(v) in for v in v_list if mapped end] 

Use nested list comprehension:

[x for x in [map_to_obj(v) for v in v_list] if x]

or better still, a list comprehension around a generator expression:

[x for x in (map_to_obj(v) for v in v_list) if x]

Python List Comprehension Setting Local Variable, You can use a nested list comprehension to define those values: output = [sum(​loss_*test_)/float(sum(loss_)) for loss_, test_ in ((do something,  With a normal list comprehension, you might find the object that you're looking for: >>> [d for d in fruits if d['name'] == 'apple'] [{'name': 'apple', 'quantity': 5}] As a result, you have a list with a single element, thanks to the if condition above.

Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's possible to use a local variable within a list comprehension in order to avoid calling twice the same function:

In our case, we can name the evaluation of map_to_obj(v) as a variable o while using the result of the expression to filter the list; and thus use o as the mapped value:

[o for v in [v1, v2, v3, v4] if (o := map_to_obj(v))]

List comprehension variable used in enclosing scope, Explicitly set the variable in the outer scope to the value that it would have held when run under Python 2. Then rename the list comprehension variable for  :-( As a workaround, you can use a trick similar to this one to 'import' your locals into the list comprehension body: [l['r'](x) for l in (locals(),) for x in l['some_local']] assuming 'r' & 'some_local' are two local variables in your surrounding scope.

You can avoid re-calculation by using python built-in filter:

list(filter(lambda t: t is not None, map(map_to_obj, v_list)))

Issue 21161: list comprehensions don't see local variables in pdb in , To make the code in pdb compile "as if" it was put in the debugged function will be as good as impossible, so I'm closing this as won't fix. List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce(). For most people the syntax of list comprehension is easier to be grasped. Examples In the chapter on lambda and map() we had designed a map() function to convert Celsius values into Fahrenheit and vice versa. It looks like this with list comprehension:

A variable assignment is just a singular binding:

[x   for v in l   for x in [v]]

This is a more general answer and also closer to what you proposed. So for your problem you can write:

[x   for v in v_list   for x in [map_to_obj(v)]   if x]

[py] local variable use in list comprehension not highlighted · Issue , [x for x in blah] Note that in python 2 (which is the main target of this mode) list/set​/dict comprehensions leak the index variable(s) to the  List comprehensions provide a concise way to create lists. It consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The expressions can be anything, meaning you can put in all kinds of objects in lists. The result will be a new list resulting from evaluating

A local variable can be set within a comprehension by cheating a bit and using an extra 'for' which "iterates" through a 1-element tuple containing the desired value for the local variable. Here's a solution to the OP's problem using this approach:

[o for v in v_list for o in (map_to_obj(v),) if o]

Here, o is the local variable being set equal to map_to_obj(v) for each v.

In my tests this is slightly faster than Lying Dog's nested generator expression (and also faster than the OP's double-call to map_to_obj(v), which, surprisingly, can be faster than the nested generator expression if the map_to_obj function isn't too slow).

List Comprehensions in Python 3, List comprehensions offer a succinct way to create lists based on existing lists. In this tutorial A list, or other iterable, is assigned to a variable. Our list comprehension takes the nested for loops and flattens them into one line of code while still creating the exact same list to assign to the my_list variable. List comprehensions provide us with a succinct way of making lists, enabling us to distill several lines of code into a single line.

Comprehensions, List comprehensions, a shortcut for creating lists, have been in Python since expressions; then 2.7 (and 3.0) introduced set and dict comprehensions. In Python 2, the iteration variable(s) of list comprehensions were considered local to the  Next, we need a unique list of games to identify the different number of columns required. This can be achieved through set comprehension. Sets are collection of unique elements. Refer to this article for basics of python data structures. #Initialize the set skills_unq = set() #Update each entry into set.

How (Not?) to Use Python's List Comprehensions, Lesser known is that you can have nested list comprehensions, that the puzzle boiled down to solving a set of 12 equations in 18 variables,  A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical set-builder notation ( set comprehension) as distinct from the use of map and filter functions.

Python - List Comprehensions, A list comprehension is a single expression that combines an expression, for statement The for-clause at assigns each value in this sequence to the local variable v . Typically, the expression depends on the variable set in the for-​clause . In the above example, a new list is assigned to variable h_letters, and list contains the items of the iterable string 'human'. We call print () function to receive the output. Syntax of List Comprehension. [expression for item in list] We can now identify where list comprehensions are used. If you noticed, human is a string, not a list. This

  • It is a fine answer, and of course it is the same as behzad's one, with list comprehensions in place of map and filter... I' going to upvote as I liked how Lying Dog translated filter in terms of l-c, but the OP may approve either one of those answers as both are fine, useful answers.
  • The inner comprehension should be a generator expression. No need to build the entire list and only then throw away the empty items to build yet another list.
  • @Lying Imho Tim's advice is sound and meaningful, please consider editing your answer to reflect his suggestion.
  • @cowbert: If a lambda (actually any Python implemented function that the comprehension could inline to avoid the call overhead) is involved, yes, the listcomp wins. map/filter can win if the callback function is a C built-in though, as they can push all the work to the C layer, bypassing bytecode interpreter overhead, which listcomps cannot avoid, as they're Python level functions, just with direct bytecode support for the append-to-list step.
  • Silly example: Changing behzad's answer to replace lambda t: t is not None with None.__ne__, while ever-so-slightly weird in how it works (it returns False for other Nones, and NotImplemented, which happens to be truthy, for everything else), would improve the speed of that solution (in local tests, the filter work drops by nearly a factor of 2), though at the expense of comprehensibility.
  • Is there a one-iteration solution?
  • @HaoTan not in python 3; in python 3, map returns a map object not a list, and filter returns a filter object; so, this will chain the functions without making intermediate lists.
  • Is it possible to use reduce to do the job?
  • @HaoTan: Why would you? reduce is for combining many things down to one thing, not for changing many things to many things. The work done by a paired map and filter (that is then listified) is equivalent to that done by a listcomp that performs both filtering and mapping operations.
  • This differs from my answer only by using a 1-element list instead of a 1-element tuple, and I think tuple beats list when it doesn't need to be mutable. :-)
  • You can use the timeit module to time the different solutions, but your above snippet is an arbitrarily overcomplexificated way to do a very simple thing - and I doubt it will be either faster or more space-efficient than the plain old for loop or the filter/imap solutions...
  • @Bruno I like your «overcomplexificated» !
  • If I look at the no itertools answers, performance notwithstanding, I dare say Lying Dog's one is the most expressive of the intent, and hence the most readable. And what about performance? well, I don't know how much cpu you spend in your f(lst) calls but removing the Nones one way or another is unlikely to change the whole picture.
  • reduce really isn't called for here. It's use is for reducing a list of values to a single value (typically, a list of scalars to a single scalar), not transforming one list into another list.