Python List with if Condition - python

I have two lists and I want to use both in if condition together.
In case only One list this can do easily
like if list_name : # if list a :
for more than 2 lists this method is not working.
although we can use separately if or using len(a) like comparison.
I am searching for simple & beautiful result.
a = [1,2,34]
b= [4,5,6,3]
# if a & b : # i was expecting this will work <br>
#if (a is True) & (b == True): # this all not working <br>
# if (len(a) >=1) & (len(b) >=1): # This will work but not beautiful <br>
#
print("Not Working") #
print("working ")

In Python, instead of using & in if statements, we use and.
This is how you can check both lists in the same if:
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
if a and b:
print("a and b are both valid!")
You can read more about Python if statements here.

Inside if-statements, lists are automatically evaluated as True or False, depending on whether they are empty or not. Therefore, we can simply write:
a = [1,2,34]
b = [4,5,6,3]
if a and b:
print('Hello World')
If you want to check if any list is non-empty, you can write a or b alternatively.
More information about the evaluation of if-statements:
What is Truthy and Falsy? How is it different from True and False?

Python has a very fancy way, working with lists.
Here are some very basic ones:
a = [1, 2, 3, 4]
b = [4, 5, 6, 7]
if a and b:
# Checks if there is something inside both lists
# returns True if there is at least 1 value inside every list
print("A and B not empty")
if a or b:
# Checks if there is something at least in one list
# returns True if there is at least 1 value inside of one list
print("Something in A or B")
if a[0] == b[0]:
# Checks the first value of both lists
print("Value 1 of A and B are equal")
# Loops through the list of a / you can use i as index
for i in range(len(a)):
if a[i] == b[i]:
print(f"{a[i]} is equal to {b[i]}")
# Alternative loop
for item in a:
print(item)

Related

Don't understand cause of TypeError when trying to use my is_descending() function

Function is_descending, which accepts one parameter list and checks if it is a descending sequence i.e. the first element in the list must be bigger than the second, the second bigger than the third, the third bigger than the fourth, etc... The return value is True/False.
def is_descending(a):
for i in range(len(a) - 1):
if a[i] < a[i + 1]:
return False
elif a[i] > a[i + 1]:
return True
assert is_descending(3, 4) == False
assert is_descending(5, 5) == False
assert is_descending(10, 1) == True
assert is_descending(10, 8, 7, 6, 1, -10, -20) == True
assert is_descending(10, 8, 7, 6,6, 1, -10, -20) == False
assert is_descending(1) == True
terminal writes:
TypeError: is_descending() takes 1 positional argument but 2 were given
Any advice on how to edit my code? I want to work with only 1 parameter.
Your function needs a to be a list.
Instead of is_descending(3, 4) that passes 2 parameters (2 integers), use is_descending([3, 4]).
Also the function should only return True once the whole list has been checked. Here only the first check matters as using return stops the loop without checking for other pairs of values.
Instead you can remove the elif block and return True outside of the for loop to wait for all the checks to be passed successfully.
Also a simpler way to achieve this would be to check if the list is sorted in reversed order (i.e. does it change after being sorted):
def is_reversed(a):
return a == sorted(a, reverse=True)

in over multiple lists [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 3 years ago.
I was recently confused by this
if 2 in ([1,2] or [3,4]) : print(True)
else: print(False)
#prints True
or is a boolean operator so how can it be applied to lists?
why does it work the same as if 2 in [1,2] or [3,4]?
Use any()
print(any(2 in x for x in [[1, 2], [3, 4]]))
or is operates on any types, not just booleans. It returns the leftmost operand that's truthy, or False if none of the operands are truthy. So ([1, 2] or [3, 4]) is equivalent to [1, 2] because any non-empty list is truthy.
In general, operators don't automatically distribute in programming languages like they do in English. x in (a or b) is not the same as x in a or x in b. Programming languages evaluate expressions recursively, so x in (a or b) is roughly equivalent to:
temp = a or b
x in temp
Both statement are different.
In first case python will first run 2 in [1,4] its False so now it will check for bool([1,3]) and its True so it prints 1.
But for second case what happening is first ([1,4] or [1,3]) is executing and this return first non-empty list. And so it will return [1,4] but 2 is not in list so nothing gets printed.
Its all about execution order.
Look at two more examples. Specially last example. ([1,4] or [2,4]) will return [1,4] and 2 is not in [1,4]. Now it will not check in second list [2,4]. If that's you want this is not the right way to do it. Use any
>>> if 2 in [1,4] or [1,3]: # True
... print(1)
...
1
>>> if 2 in ([1,4] or [1,3]): # False
... print(1)
...
>>> if 2 in [1,4] or []: # False
... print(1)
...
>>> if 2 in ([1,4] or [2,4]): # False!!
... print(1)
...

Can I assign the value of the left hand side of a Boolean expression (e.g in a while loop) to something?

Is there a syntax to capture a result evaluated in a Boolean expression? In other words, what was the result that caused the Boolean to be True?
A concrete example - I want the second largest number in a set, regardless of how often the largest number is duplicated:
nums = [1, 2, 3, 4, 4]
h = nums.pop()
while nums.pop() == h:
pass
print(nums.pop())
Obviously returns 2, because the 3 has gone in evaluating the expression. Is there something like:
while (i = nums.pop()) == h:
#Do something with i

Checking if two lists share at least one element [duplicate]

This question already has answers here:
Test if lists share any items in python
(9 answers)
Closed 4 years ago.
I have two lists, for example:
a = ["mail1", "mail2", "mail3", "mail4"]
b = ["mail2", "mail5"]
and I want to check if any of the elements in list b also appears in list a.
I wanted to know if there is a way (and what is it) to do this without a for loop.
Also I wanted to know how can I create a list of boolean values, where each value will be the result of the comparison of values a[i] and b[i], something like:
[z for i, j in zip(a, b) z = i == j] # (just with the right syntax)
z will be 1 if in some place i == j, so I can check the array for any 'True' values.
You can use any:
any(x in a for x in b)
The nice thing about this generator expression is that any will return True as soon as the generator yields a True, i.e. there won't be redundant x in a lookups.
Edit:
You can improve the time complexity by making a set from a.
a_set = set(a)
any(x in a_set for x in b)
Regarding your new question:
[x == y for x,y in zip(a,b)]
Elegant way is to use sets:
a = ["mail1", "mail2", "mail3", "mail4"]
b = ["mail2", "mail5"]
anb = set(a) & set(b)
print anb
if anb:
print True
>>> set(['mail2'])
>>> True
The any function takes in an iterable (See documentation here), so the answer should be any([x in a for x in b])

Checking if elements exist in list using python

I am new to python and was wondering if someone could help me out with this. I am trying to see if the elements in b are in a. This is my attempt. Currently I am not getting any output. Any help would be appreciated, thank you!
a = [1]
b = [1,2,3,4,5,6,7]
for each in b:
if each not in a == True:
print(each + "is not in a")
You are testing two different things, and the outcome is False; Python is chaining the operators, effectively testing if (each is in a) and (a == True):
>>> 'a' in ['a'] == True
False
>>> ('a' in ['a']) and (['a'] == True)
False
>>> ('a' in ['a']) == True
True
You never need to test for True on an if statement anyway:
if each not in a:
is enough.
You should be able to just say:
if each not in a:
print ("%d is not in a" % each)
Your actual expression is using operator chaining:
if a > b > c:
parses as:
if (a > b) and (b > c):
in python. which means your expression is actually being parsed as:
if (each not in a) and (a == True):
but a == True will always return False, so that if block will never execute.
a = [1,2,3]
b = [1,2,3,4,5,6,7]
c = [7,8,9]
print set(a) <= set(b) #all elements of a are in b
print set(c) <= set(b) #all elements of c are in b
It is better to see the difference between B and A
set(b).difference(set(a))
You don't need ==True. Just:
if each not in a:
This is really easy using sets:
a = [1]
b = [1, 2]
only_in_b = set(b) - set(a)
# set([2])
Another way:
for bb in b:
try:
a.index(bb)
except:
print 'value is not in the list: ' + str(bb)
I would like to add that if the two lists are large. This is not the best way to do it. Your algorithm is O(n^2). The best way is to traverse a, adding the elements as keys to a dictionary. Afterwards, traverse the second list, checking if the elements are already in the dictionary, this instead is an O(n) algorithm.

Categories

Resources