generator-expression

Why results of map() and list comprehension are different?

The following test fails: #!/usr/bin/env python def f(*args): """ >>> t = 1, -1 >>> f(*map(lambda i: lambda: i, t)) [1, -1] >>> f(*(lambda: i for i in t)) # -> [-1, -1] [1, -1] >>> f(*[lambda: i for i in t]) # -> [-1, -1] [1, -1] """ alist = [a() for a in args] print(alist) if __name__ == '__...

Use case for nested/multiple list comprehensions or generator expressions. When is it more elegant?

I see this kind of thing sometimes: (k for k in (j for j in (i for i in xrange(10)))) Now this really bends my brain, and I would rather it wasn't presented in this way. Are there any use-cases, or examples of having used these nested expressions where it was more elegant and more readable than if it had been a nested loop? Edit: Th...

Django Custom Queryset filters

Is there, in Django, a standard way to write complex, custom filters for QuerySets? Just as I can write MyClass.objects.all().filter(field=val) I'd like to do something like this : MyClass.objects.all().filter(customFilter) I could use a generator expression (x for x in MyClass.objects.all() if customFilter(x)) but that would...

convert string to dict using list comprehension in python

I have came across this problem a few times and can't seem to figure out a simple solution. Say I have a string string = "a=0 b=1 c=3" I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this: list = string.split() dic ...

Why is this genexp performing worse than a list comprehension?

I was trying to find the quickest way to count the number of items in a list matching a specific filter. In this case, finding how many odd numbers there are in a list. While doing this, I was surprised by the results of comparing a list comprehension vs the equivalent generator expression: python -m timeit -s "L = xrange(1000000)" "su...