Apply comparison to a list in Python? [duplicate] - python

This question already has answers here:
Check if all elements in a list are identical
(30 answers)
Closed 8 years ago.
I am trying to compare elements of a list u for equality.
A possible solution could be all(x == u[0] for x in u[1:]), or simply all(x == u[0] for x in u), but it looks rather weird.
In Python, it's possible to write a == b == c, with its usual "mathematical" meaning. So I thought I could, with the help of the operator module, write operator.eq(*u). However, the eq function takes only two arguments. Of course, functools.reduce(operator.eq, u) is of no use here, since after the first test eq(u[0], u[1]), I get a boolean, and it will fail when doing the second test, eq(<bool>, u[2]).
Is there a better way than the solution above? A more... "pythonic" way?

len(set(u)) == 1 is pretty Pythonic.

Related

What's the name of this operator in Python? [duplicate]

This question already has answers here:
Python list - True/False first two elements? [duplicate]
(2 answers)
Closed 2 years ago.
In a Clash of Code, I've seen this interesting operator thing:
print(["false","true"][i == n])
I haven't seen this before. What's the name of this and what does it do?
It's not exactly an operator but rather the second condition is being used as an index for the ["false", "true"] list.
In case i == n this will be true. Let me remind you that true in python equals to 1
int(True) // = 1
Therefore if i == n, it will be equal to one and will print the element with index one from the list which is "true".
In case i != n, it will be False, equals to 0 which will print the first element from the array which is "false".
This a comparison Operator,
it compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None.
Output: True or False
Usage: Is used to check whether 2 expressions give the same value.

Conditional with list comprehension (NOT list comprehension with conditional) in python [duplicate]

This question already has answers here:
How do Python's any and all functions work?
(10 answers)
Closed 3 years ago.
Just thought I would specify in the title, because I have found the latter all over the internet, but not the former. I am curious how to get a conditional that contains a list comprehension working in python. Specifically, I am curious about how to do something like the following:
if (abs(value - any_x)) > 100 for any_x in x:
Essentially, I want the program to proceed if the absolute value of the difference between the value and any value in the x array is greater than 100. But the syntax as it stands is incorrect. What exactly am I missing? Thanks and best regards,
-AA
Use any:
if any(abs(value - any_x) > 100 for any_x in x):
...
Don't use a list comprehension here as any will return True on the first True value it finds. Thus providing it a generator is the most efficient method as it will be lazily evaluated.
You can use any.
if any(abs(value - any_x) > 100 for any_x in x):
Pretty simple,
True in [abs(k-value)>100 for k in x]

List comprehension and intersection problem [duplicate]

This question already has answers here:
Best way to find the intersection of multiple sets?
(7 answers)
Closed 3 years ago.
list(set(a[0]) & set(a[1]) & set(a[2]) & set(a[3]) & set(a[4]))
Does anyone know how to write this in a way such that we dont need to know apriori how many lists we will be given? (ie 5 not hard coded in)?
Each a is a list of varying size.
As long as you have at least one set, you can do this:
list(set(a[0]).intersection(*a[1:]))
If there might be no sets, you have to decide for yourself what the "intersection of no sets" actually should mean in your application. If you want the empty set:
list(set(*a[:1]).intersection(*a[1:]))
I think it's worth noting, at least to improve one's general programming understanding, that what you want to do can be described as mapping and then reducing or folding. Specifically, you want to map set over a and then fold & over the result.
I'm not a Python expert, but it can be done like this in Python:
from functools import reduce
a = [
[1,2,3],
[1,2,3,4],
[1,2,4,5],
[1,2,3,5],
]
intersection = lambda x, y: x & y
mapped = list(map(set, a))
reduced = reduce(intersection, mapped)
Note that this implementation requires a to be non-empty.

If N is equal to an integer [duplicate]

This question already has answers here:
What's the canonical way to check for type in Python?
(15 answers)
Closed 5 years ago.
I'm currently writing a function that runs through a list of elements, and only does operation on list elements that are integers. It looks like this:
for n in list1:
if n == int:
#Do stuff
What I'm struggling with is how to actually write out the loop to detect if the element is an integer. What should I do for this? I can't find anything in the docs of Python (Although maybe I haven't looked deep enough in).
Thanks for any help.
Use the isinstance() function:
for n in list1:
if isinstance(n, int):
# Do stuff
for n in list1:
if isinstance( n, ( int, long )):
#dostuff

Using list comprehension for repeated function calls in Python [duplicate]

This question already has answers here:
Is it Pythonic to use list comprehensions for just side effects?
(7 answers)
Closed 6 years ago.
In my current codebase, I have the following line where to_remove is a set
[to_remove.update(b) for b in some_set if all(a <= b for a in some_dict)]
Although it works, it bothers me a little bit since it creates a list of None which is not used. Is it considered not standard? Is there a better way to do it?
Update:
Since it has been pointed out that list comprehension solely for side effect is not good, I have changed my code to
to_remove.update(itertools.chain.from_iterable(
b for b in some_set if all(a <= b for a in some_dict))
It's not standard or recommended to use a list comprehension if its output is not assigned to a variable. A static analyzer such as pylint will even flag it.
Use a conventional loop instead:
for b in some_set:
if all(a <= b for a in some_dict):
to_remove.update(b)
In your specific case, since to_remove is a set, the following may or may not work correctly:
to_remove.update(b for b in some_set if all(a <= b for a in some_dict))

Categories