Get actual value from Python list - python

Say I have
a = [1,2,3]
b = [foo(x) for x in a]
Now b is something like [ < function at 0x00F91540>, ...], how do I get python to evaluate b into it's actual values?
--EDIT--
Sorry for the confusion, my frustration is that Python doesn't give me the actual values in b, hence when I try to do something like:
b[0] + 1
it gives me the below error:
TypeError: unsupported operand type(s) for +: 'function' and 'int'

Define your function outside the comprehension:
def foo(x):
return x + 1
a = [1,2,3]
b = [foo(x) for x in a]
Now, b == [2,3,4]. Or, as others have pointed out, just use the function body in the list comprehension:
[x + 1 for x in a]
...although this assumes that you can reproduce the function body in this way (which you won't be able to do for more complicated functions).
Note that the result of a lambda expression is the same as typing the name of a function, eg. lambda x: x+1 and foo represent the same thing: a function which needs a parameter given to it and returns a result. For the sake of clarification, this is how you'd "use" a lambda in a list comprehension:
[(lambda y: y+1)(x) for x in a]
...but seriously, don't do this ;)

If you just want the values, you don't need lambdas at all.
You can simply write:
b = [x + 1 for x in a]
If, for some reason, you still want to evaluate the lambdas that are in your version of b, you can write something like this:
c = [f(n) for f, n in zip(b, a)]

If I understand what you want it to do correctly, you don't need the lambda.
b = [x+1 for x in a]
should do what you want.

What you are doing is creating a list of lambda functions what you want is
a = [1,2,3]
b = [x+1 for x in a]

Related

Access elements in a Python tuple

I have a tuple like this:
('TRM',)
I would like to extract the string only from this tuple.
I did the following and it works but just thinking if there is a better way to do that.
>>> b = [x for x in a]
>>> b
['TRM']
>>> for i in b:
... print(i)
...
TRM
>>>
This will help you
b = [x for x in a if type(x) == type("Str")]
print(b)
If you need to access a specific element of the tuple you can do it by index:
>>> a[0]
TRM
Not exactly sure what you're asking for but you could do:
for i in b:
if isinstance(i, str):
print(i)
and this will print
TRM
Edit: Now it checks whether an element is a string.

For loop in python using brackets

There is a formatting question, that I would like some additional insight/understanding on. I have the following code:
In[1]:
mylist = [[99]]
for [x] in mylist:
print(x)
Out[1]:
99
My main question is regarding the []s around the x in the second line. So I have never used []s before when describing the 'x' variable of a loop. Since my output is 99 and not [99], it looks like the []s are going to ask the loop to extract the number from its additional set of brackets.
Question Updated Based on Responses:
If I change the code to remove the brackets:
In[1]:
mylist = [[99]]
for x in mylist:
print(x)
Out[1]:
[99]
I get [99] instead of 99. However, if I do the following:
In[1]:
mylist = [[99,100]]
for x,y in mylist:
print(x)
print(y)
Out[1]:
99
100
This example above doesn't require an additional set of []s around x,y and produces a bracket-less answer in the output, unlike the previous two examples, which requires a [] to produce a bracket-less answer.
I realize this is an odd and fairly silly question since I would never construct a single element list like this. I simply saw this being casually used in an answer elsewhere online (with no explanation on it unfortunately). Being a newcomer, I'm just curious to broaden my understanding of the language.
Thanks in advance.
When you do this:
>>> myList = [[99]]
>>> for x in myList:
print x
Python interprets that as "print each element in this iterable".
When you do this:
>>> myList = [[99,100], [99,101], [99, 102]]
>>> for x in myList:
print x
Python still interprets that as "print each element in this iterable" so that you get this:
[99, 100]
[99, 101]
[99, 102]
But, if you do this:
>>> myList = [[99,100], [99,101], [99, 102]]
>>> for x, y in myList:
print x, y
Python will "unpack" the values for you from each element in the iterable and assign them to x and y. If you want to do that above for only the case of myList = [[99]], Python requires the for [x] in myList syntax so that it unpacks the single value from the list.
The ability to "unpack" an iterable is very powerful in Python. You can assign variables on the fly by unpacking an iterable. In your case, you can imagine having to assign lat lon as variables maybe or something else. You can also unpack values into the args of a function.
In Python 3 you can also do something like this:
x = [1,2,3,4]
first, *rest = x
print (first) # 1
print (rest) # [2,3,4]
For the second example, with lists of length 2, to unpack both values you can do
In[1]:
myList = [[99,100]]
for x, y in myList:
print(x)
print(y)
Out[1]:
99
100
As per Python documentation, the square brackets are essentially ignored in assignments and loop constructs.
So as a complement to user2774697's answer, for x, y in L is equivalent to for [x, y] in L which is equivalent to for ([x, y]) in L and is also equivalent to for (x, y) in L.
The thing that the square brackets do different than a bare round parenthesis is that it enforces an unpacking behavior, it requires the elements in L to be iterable.

Python find all sub arrays of an array, that have length greater than 1 [duplicate]

I want to compare 2 iterables and print the items which appear in both iterables.
>>> a = ('q', 'r')
>>> b = ('q')
# Iterate over a. If y not in b, print y.
# I want to see ['r'] printed.
>>> print([ y if y not in b for y in a])
^
But it gives me a invalid syntax error where the ^ has been placed.
What is wrong about this lamba function?
You got the order wrong. The if should be after the for (unless it is in an if-else ternary operator)
[y for y in a if y not in b]
This would work however:
[y if y not in b else other_value for y in a]
You put the if at the end:
[y for y in a if y not in b]
List comprehensions are written in the same order as their nested full-specified counterparts, essentially the above statement translates to:
outputlist = []
for y in a:
if y not in b:
outputlist.append(y)
Your version tried to do this instead:
outputlist = []
if y not in b:
for y in a:
outputlist.append(y)
but a list comprehension must start with at least one outer loop.
list comprehension formula:
[<value_when_condition_true> if <condition> else <value_when_condition_false> for value in list_name]
thus you can do it like this:
[y for y in a if y not in b]
Only for demonstration purpose :
[y if y not in b else False for y in a ]
This is not a lambda function. It is a list comprehension.
Just change the order:
[ y for y in a if y not in b]
If you use sufficiently big list not in b clause will do a linear search for each of the item in a. Why not use set? Set takes iterable as parameter to create a new set object.
>>> a = ["a", "b", "c", "d", "e"]
>>> b = ["c", "d", "f", "g"]
>>> set(a).intersection(set(b))
{'c', 'd'}

python sort a list of objects based on attributes in the order of the other list

I am working with Python list sort.
I have two lists: one is a list of integers, the other is a list of objects, and the second object list has the attribute id which is also an integer, I want to sort the object list based on the id attribute, in the order of the same id appears in the first list, well, this is an example:
I got a = [1,2,3,4,5]
and b = [o,p,q,r,s], where o.id = 2, p.id = 1, q.id = 3, r.id = 5, s.id = 4
and I want my list b to be sorted in the order of its id appears in list a, which is like this:
sorted_b = [p, o, q, s, r]
Of course, I can achieve this by using nested loops:
sorted_b = []
for i in a:
for j in b:
if j.id == i:
sorted_b.append(j)
break
but this is a classic ugly and non-Python way to solve a problem, I wonder if there is a way to solve this in a rather neat way, like using the sort method, but I don't know how.
>>> from collections import namedtuple
>>> Foo = namedtuple('Foo', 'name id') # this represents your class with id attribute
>>> a = [1,2,3,4,5]
>>> b = [Foo(name='o', id=2), Foo(name='p', id=1), Foo(name='q', id=3), Foo(name='r', id=5), Foo(name='s', id=4)]
>>> sorted(b, key=lambda x: a.index(x.id))
[Foo(name='p', id=1), Foo(name='o', id=2), Foo(name='q', id=3), Foo(name='s', id=4), Foo(name='r', id=5)]
This is a simple way to do it:
# Create a dictionary that maps from an ID to the corresponding object
object_by_id = dict((x.id, x) for x in b)
sorted_b = [object_by_id[i] for i in a]
If the list gets big, it's probably the fastest way, too.
You can do it with a list comprehension, but in general is it the same.
sorted_b = [ y for x in a for y in b if y.id == x ]
There is a sorted function in Python. It takes optional keyword argument cmp. You can pass there your customized function for sorting.
cmp definition from the docs:
custom comparison should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument
a = [1,2,3,4,5]
def compare(el1, el2):
if a.index(el1.id) < a.index(el2.id): return -1
if a.index(el1.id) > a.index(el2.id): return 1
return 0
sorted(b, cmp=compare)
This is more straightforward however I would encourage you to use the key argument as jamylak described in his answer, because it's more pythonic and in Python 3 the cmp is not longer supported.

How to run an operation on a collection in Python and collect the results?

How to run an operation on a collection in Python and collect the results?
So if I have a list of 100 numbers, and I want to run a function like this for each of them:
Operation ( originalElement, anotherVar ) # returns new number.
and collect the result like so:
result = another list...
How do I do it? Maybe using lambdas?
List comprehensions. In Python they look something like:
a = [f(x) for x in bar]
Where f(x) is some function and bar is a sequence.
You can define f(x) as a partially applied function with a construct like:
def foo(x):
return lambda f: f*x
Which will return a function that multiplies the parameter by x. A trivial example of this type of construct used in a list comprehension looks like:
>>> def foo (x):
... return lambda f: f*x
...
>>> a=[1,2,3]
>>> fn_foo = foo(5)
>>> [fn_foo (y) for y in a]
[5, 10, 15]
Although I don't imagine using this sort of construct in any but fairly esoteric cases. Python is not a true functional language, so it has less scope to do clever tricks with higher order functions than (say) Haskell. You may find applications for this type of construct, but it's not really that pythonic. You could achieve a simple transformation with something like:
>>> y=5
>>> a=[1,2,3]
>>> [x*y for x in a]
[5, 10, 15]
Another (somewhat depreciated) method of doing this is:
def kevin(v):
return v*v
vals = range(0,100)
map(kevin,vals)
List comprehensions, generator expressions, reduce function.

Categories

Resources