What is the and operator in Python?

Discover the and logical operator in Python: syntax, how it works, short-circuit evaluation, practical examples, and best practices for your conditions.
9 min read
Believemy logo

Definition of the and operator in Python

The and operator is a logical operator in Python that allows you to combine two or more conditions. It returns True only if all the conditions evaluated are true. If any one of them is false, the entire expression returns False.

This operator is fundamental in Python programming and you will find it in virtually all programs, from the simplest to the most complex. If you want to master Python from A to Z, our comprehensive Python course will guide you step by step through learning these essential concepts.

In Boolean logic, and corresponds to the logical conjunction. Here is its truth table:

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

As you can see, the result is True only when both operands are true simultaneously.


Syntax and basic usage

The syntax of the and operator is very simple and readable, which is consistent with Python's philosophy:

PYTHON
condition1 and condition2

You can use it directly in conditional structures with if, in loops, or even in variable assignments. Here is a first simple example:

PYTHON
age = 25
income = 35000

if age >= 18 and income >= 30000:
    print("You are eligible for the loan.")
else:
    print("You are not eligible.")

In this example, both conditions must be met for the eligibility message to be displayed. If the age is less than 18 or the income is less than 30,000, the result will be False.


Combining multiple and operators

You can chain as many conditions as needed with and:

PYTHON
name = "Alice"
age = 30
city = "Paris"
is_active = True

if name and age >= 18 and city == "Paris" and is_active:
    print("Valid and active profile in Paris.")
Good to know

When you chain multiple conditions with and, Python evaluates them from left to right and stops as soon as a condition is false. This is called short-circuit evaluation.


Short-circuit evaluation

One of the most important aspects of the and operator in Python is its short-circuit evaluation mechanism. Python does not evaluate all conditions if it is not necessary:

  • If the first condition is False, Python immediately returns that value without evaluating the rest.
  • If the first condition is True, Python moves to the next condition and continues until it finds a falsy value or reaches the end.
PYTHON
def check_a():
    print("Checking A")
    return False

def check_b():
    print("Checking B")
    return True

result = check_a() and check_b()
# Prints only: "Checking A"
# check_b() is never called

This behavior is extremely useful for protecting your code against errors. Here is a concrete example:

PYTHON
my_list = []

# Without short-circuit evaluation, this would cause an error
if my_list and my_list[0] > 10:
    print("The first element is greater than 10.")
else:
    print("Empty list or first element <= 10.")

Here, since my_list is empty (thus evaluated as False), Python never tries to access my_list[0], which would have caused an IndexError.

Warning

Short-circuit evaluation is a powerful tool, but be careful not to overuse it. Code that is too dependent on evaluation order can become difficult to read and maintain.


Return values of and: beyond booleans

A point often unknown to beginners: the and operator in Python does not always return True or False. It actually returns the actual value of one of the operands:

  • If the first operand is falsy, it is returned directly.
  • If the first operand is truthy, the second operand is returned.
PYTHON
# With non-boolean values
print(0 and 42)          # 0 (0 is falsy)
print("" and "Hello")     # "" (empty string is falsy)
print("Hello" and "World") # "World" (both are truthy)
print(5 and 0)            # 0 (5 is truthy, returns the second)
print([] and [1, 2, 3])   # [] (empty list is falsy)
print(None and "text")    # None (None is falsy)

This behavior allows for elegant Python idioms to assign values conditionally:

PYTHON
user = {"name": "Alice", "email": "alice@example.com"}

# Get the email only if the name exists
email = user.get("name") and user.get("email")
print(email)  # alice@example.com


Truthy and falsy values in Python

To use and effectively, it is essential to know which values Python considers as falsy:

ValueTypeBoolean evaluation
FalseboolFalsy
NoneNoneTypeFalsy
0intFalsy
0.0floatFalsy
""strFalsy
[]listFalsy
()tupleFalsy
{}dictFalsy
set()setFalsy

Any other value is considered truthy.


Advanced practical examples

Form validation

The and operator is widely used to validate form data:

PYTHON
def validate_registration(name, email, password):
    if name and email and password:
        if len(name) >= 2 and "@" in email and len(password) >= 8:
            return True
    return False

# Tests
print(validate_registration("Alice", "alice@mail.com", "password123"))  # True
print(validate_registration("", "alice@mail.com", "password123"))       # False
print(validate_registration("Alice", "alice@mail.com", "short"))        # False


Data filtering with and

You can use and in list comprehensions to filter data:

PYTHON
employees = [
    {"name": "Alice", "age": 30, "department": "IT", "active": True},
    {"name": "Bob", "age": 25, "department": "HR", "active": False},
    {"name": "Charlie", "age": 35, "department": "IT", "active": True},
    {"name": "Diana", "age": 28, "department": "IT", "active": True},
]

# Active employees in the IT department older than 27
result = [
    e["name"] for e in employees
    if e["department"] == "IT" and e["active"] and e["age"] > 27
]

print(result)  # ['Alice', 'Charlie', 'Diana']


Chained comparisons with and

Python allows you to chain comparisons in a very elegant way, which is equivalent to using and:

PYTHON
grade = 15

# These two syntaxes are equivalent
if 10 <= grade <= 20:
    print("Valid grade")

if grade >= 10 and grade <= 20:
    print("Valid grade")
Good to know

The chained syntax 10 <= grade <= 20 is syntactic sugar specific to Python. Internally, Python converts it to grade >= 10 and grade <= 20.


Usage with lambda functions

The and operator combines very well with lambda functions and higher-order functions like filter():

PYTHON
numbers = range(-10, 11)

# Filter positive AND even numbers
positive_even = list(filter(lambda x: x > 0 and x % 2 == 0, numbers))
print(positive_even)  # [2, 4, 6, 8, 10]


Difference between and, or, and not

Python has three logical operators. It is important to distinguish them clearly:

OperatorDescriptionExampleResult
andTrue if both are trueTrue and FalseFalse
orTrue if at least one is trueTrue or FalseTrue
notInverts the valuenot TrueFalse


Operator precedence

Logical operators have a precedence order in Python:

  1. not (highest precedence)
  2. and
  3. or (lowest precedence)
PYTHON
# Without parentheses
result = True or False and False
print(result)  # True
# Equivalent to: True or (False and False) → True or False → True

# With parentheses to force the order
result = (True or False) and False
print(result)  # False
# (True or False) → True, then True and False → False
Warning

Always use parentheses when combining and and or in the same expression. This makes your code clearer and avoids subtle errors related to operator precedence.


Difference between and and &

A frequent confusion concerns the difference between and and &:

  • and is a logical operator that works on boolean values and uses short-circuit evaluation.
  • & is a bitwise operator that works on individual bits of integers.
PYTHON
# Logical operator and
print(True and False)  # False
print(5 and 3)         # 3 (returns the second since 5 is truthy)

# Bitwise operator &
print(True & False)    # False
print(5 & 3)           # 1 (0101 & 0011 = 0001 in binary)
Warning

Never use & instead of and for logical operations. The behavior is different and can lead to hard-to-detect bugs.


Best practices

Here are the essential recommendations for using and effectively in Python:

  • Place the least expensive condition first: thanks to short-circuit evaluation, if the first condition is false, the following ones will not be evaluated. Place simple checks before expensive function calls.
  • Use parentheses to clarify complex expressions, even if they are not strictly necessary.
  • Avoid overly long lines: if you have more than 3 conditions, consider storing them in intermediate variables.
  • Prefer readability: never sacrifice code clarity to save a line.
  • Document complex conditions with comment or docstring to explain the business logic.
PYTHON
# ❌ Bad practice: too many conditions on one line
if a > 0 and b > 0 and c > 0 and d > 0 and e > 0 and f > 0:
    process()

# ✅ Good practice: use intermediate variables
all_positive = all([a > 0, b > 0, c > 0, d > 0, e > 0, f > 0])
if all_positive:
    process()

# ✅ Good practice: split across multiple lines
if (a > 0
        and b > 0
        and c > 0
        and d > 0):
    process()


Using all() as an alternative

When you need to verify that all conditions are true in a list, the built-in all() function is an elegant alternative to multiple and operators:

PYTHON
conditions = [
    age >= 18,
    income >= 30000,
    credit_score >= 700,
    no_debts,
]

# Equivalent to: age >= 18 and income >= 30000 and ...
if all(conditions):
    print("All conditions are met.")
Good to know

Note: unlike and, all() evaluates all expressions in the list before checking. Short-circuit evaluation does not apply here, unless you use a generator.


Frequently asked questions

Question

What is the difference between and and or in Python?

The and operator returns True only if all conditions are true, while or returns True if at least one condition is true. In terms of short-circuit evaluation, and stops at the first False encountered, while or stops at the first True.


Question

Can you use and with non-boolean types?

Yes, absolutely. The and operator works with all Python types. It evaluates values in terms of truthy/falsy. For example, "hello" and 42 returns 42, because both values are truthy and Python returns the last evaluated value. Conversely, 0 and "hello" returns 0 because it is falsy.


Question

How many conditions can you chain with and?

There is no technical limit to the number of conditions you can chain with and. However, beyond 3 or 4 conditions, we recommend using intermediate variables, the all() function, or splitting your conditions across multiple lines to maintain code readability.


Question

How can you learn to properly use logical operators in Python?

Mastering logical operators like and, or, and not requires regular practice and a solid understanding of the fundamentals. Our dedicated Python course covers logical operators, conditional structures, and many other essential concepts in depth, all accompanied by practical exercises to solidify your skills.

Related terms

Discover our python glossary

Browse the terms and definitions most commonly used in development with Python.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.