How To Compare An Input To A List In Python?

Comparing an input to a list in Python involves checking if the input exists within the list or verifying the characteristics of the list based on the input. This process ensures data integrity and proper execution of your code. At compare.edu.vn, we provide detailed guidance on effectively comparing data in Python, helping you make informed decisions. You can use comparison operators, membership tests, and loop through the list.

1. Understanding the Basics of Input Validation in Python

Validating input in Python is essential to ensure that your program receives the correct type and format of data. This process prevents errors, improves security, and enhances the overall reliability of your code.

1.1. What is Input Validation?

Input validation is the process of verifying that user-provided data meets certain criteria before it is processed by your application. This involves checking the data type, format, range, and other relevant attributes to ensure that it is safe and appropriate for your program’s logic.

1.2. Why is Input Validation Important?

Input validation is important for several reasons:

  • Preventing Errors: It helps prevent errors caused by unexpected or malformed data, ensuring smooth program execution.
  • Enhancing Security: It mitigates security risks such as SQL injection, cross-site scripting (XSS), and other malicious attacks by filtering out harmful input.
  • Ensuring Data Integrity: It maintains the integrity of your data by ensuring that only valid and consistent information is stored and processed.
  • Improving User Experience: It provides meaningful error messages to users, guiding them to provide correct input and improving the overall user experience.

1.3. Basic Techniques for Input Validation

There are several basic techniques for input validation in Python:

  • Type Checking: Verifying that the input is of the expected data type (e.g., integer, string, list).
  • Format Validation: Ensuring that the input matches a specific format (e.g., email address, phone number).
  • Range Checking: Checking that the input falls within an acceptable range of values (e.g., age between 18 and 65).
  • Membership Testing: Verifying that the input is a member of a predefined set of values (e.g., a list of valid options).
  • Regular Expressions: Using regular expressions to match complex patterns and validate input against them.

1.4. Python’s Built-in Functions for Validation

Python provides several built-in functions that can be used for input validation:

  • isinstance(): Checks if an object is an instance of a particular class or type.
  • len(): Returns the length of a string, list, or other iterable.
  • str.isdigit(): Checks if a string contains only digits.
  • str.isalpha(): Checks if a string contains only alphabetic characters.
  • str.isalnum(): Checks if a string contains only alphanumeric characters.
  • str.startswith() and str.endswith(): Checks if a string starts or ends with a specific substring.
  • in: Checks if an element is present in a sequence (e.g., list, tuple, string).

1.5. Example: Validating Input as a String

def validate_string(input_str):
    if not isinstance(input_str, str):
        raise TypeError("Input must be a string")
    if not input_str.isalpha():
        raise ValueError("Input must contain only alphabetic characters")
    return input_str

try:
    name = validate_string("John")
    print("Name:", name)  # Output: Name: John
    name = validate_string("John123")
except ValueError as e:
    print("Error:", e)  # Output: Error: Input must contain only alphabetic characters
except TypeError as e:
    print("Error:", e)

This example validates that the input is a string and contains only alphabetic characters. If the input does not meet these criteria, it raises a ValueError or TypeError with a descriptive error message.

1.6. Example: Validating Input as an Integer

def validate_integer(input_int):
    if not isinstance(input_int, int):
        raise TypeError("Input must be an integer")
    if input_int <= 0:
        raise ValueError("Input must be a positive integer")
    return input_int

try:
    age = validate_integer(30)
    print("Age:", age)  # Output: Age: 30
    age = validate_integer(-5)
except ValueError as e:
    print("Error:", e)  # Output: Error: Input must be a positive integer
except TypeError as e:
    print("Error:", e)

This example validates that the input is an integer and is a positive number. If the input does not meet these criteria, it raises a ValueError or TypeError with a descriptive error message.

1.7. Input Validation Libraries

For more complex validation scenarios, you can use third-party libraries such as:

  • Voluptuous: A Python data validation library.
  • Cerberus: A lightweight and extensible data validation library.
  • Schema: A library for validating Python data structures.

These libraries provide powerful tools for defining validation schemas, handling errors, and ensuring that your input data is valid and consistent.

1.8. Common Validation Scenarios

Some common validation scenarios include:

  • Email Validation: Verifying that an email address is properly formatted.
  • Phone Number Validation: Ensuring that a phone number follows a specific format.
  • Date Validation: Checking that a date is valid and falls within an acceptable range.
  • URL Validation: Verifying that a URL is correctly formatted and accessible.

By implementing robust input validation techniques, you can create more reliable, secure, and user-friendly Python applications.

2. Defining Type Hints in Python

Type hints in Python are annotations that specify the expected type of a variable, function argument, or function return value. They enhance code readability, facilitate static analysis, and enable better error detection.

2.1. Introduction to Type Hints

Type hints were introduced in Python 3.5 as a way to add static type information to Python code. Unlike languages like Java or C++, Python is dynamically typed, meaning that the type of a variable is determined at runtime. Type hints allow you to provide optional type information that can be used by type checkers like mypy to verify the correctness of your code.

2.2. Basic Syntax for Type Hints

The basic syntax for adding type hints to variables, function arguments, and return values is as follows:

  • Variable Type Hints:
name: str = "John"
age: int = 30
price: float = 99.99
is_active: bool = True
  • Function Argument Type Hints:
def greet(name: str, age: int) -> str:
    return f"Hello, {name}! You are {age} years old."
  • Function Return Type Hints:
def add(x: int, y: int) -> int:
    return x + y

In these examples, : str, : int, : float, and : bool are type hints that specify the expected type of the variable or function argument. -> str and -> int specify the return type of the function.

2.3. Using Type Hints with Collections

Type hints can also be used with collections like lists, tuples, and dictionaries. The typing module provides specific types for these collections.

  • List Type Hints:
from typing import List

names: List[str] = ["John", "Jane", "Mike"]
ages: List[int] = [30, 25, 35]
  • Tuple Type Hints:
from typing import Tuple

person: Tuple[str, int] = ("John", 30)
  • Dictionary Type Hints:
from typing import Dict

person_info: Dict[str, str] = {"name": "John", "age": "30"}

2.4. Using Optional Type Hint

The Optional type hint is used to indicate that a variable or function argument can be either a specific type or None.

from typing import Optional

def get_name(name: Optional[str] = None) -> str:
    if name is None:
        return "No name provided"
    return f"Name: {name}"

In this example, the name argument can be either a string or None.

2.5. Using Union Type Hint

The Union type hint is used to indicate that a variable or function argument can be one of several different types.

from typing import Union

def process_data(data: Union[int, str]) -> str:
    if isinstance(data, int):
        return f"Integer data: {data}"
    elif isinstance(data, str):
        return f"String data: {data}"
    else:
        return "Unsupported data type"

In this example, the data argument can be either an integer or a string.

2.6. Benefits of Using Type Hints

Using type hints in Python provides several benefits:

  • Improved Code Readability: Type hints make it easier to understand the expected types of variables and function arguments, improving code readability.
  • Static Analysis: Type checkers like mypy can use type hints to perform static analysis and detect type-related errors before runtime.
  • Better IDE Support: IDEs can use type hints to provide better code completion, error highlighting, and other helpful features.
  • Reduced Runtime Errors: By catching type errors early, type hints can help reduce the number of runtime errors in your code.

2.7. Example: Using Type Hints in a Function

from typing import List

def process_names(names: List[str]) -> List[str]:
    """
    Processes a list of names and returns a list of uppercase names.
    """
    uppercase_names: List[str] = [name.upper() for name in names]
    return uppercase_names

names: List[str] = ["John", "Jane", "Mike"]
uppercase_names: List[str] = process_names(names)
print(uppercase_names)  # Output: ['JOHN', 'JANE', 'MIKE']

This example demonstrates how to use type hints with a function that processes a list of names. The type hints specify that the function expects a list of strings as input and returns a list of strings.

2.8. Type Checking with mypy

To take full advantage of type hints, you can use a type checker like mypy. mypy is a static type checker that can analyze your Python code and identify type-related errors.

To use mypy, you first need to install it:

pip install mypy

Then, you can run mypy on your Python code:

mypy your_file.py

mypy will analyze your code and report any type errors it finds.

2.9. Common Type Hinting Mistakes

Some common mistakes to avoid when using type hints include:

  • Forgetting to Import Types: Make sure to import types from the typing module when using collections like List, Tuple, and Dict.
  • Incorrect Type Annotations: Double-check that your type annotations accurately reflect the expected types of your variables and function arguments.
  • Ignoring Type Checker Errors: Pay attention to the errors reported by your type checker and fix them to ensure the correctness of your code.
  • Overusing Any Type: Avoid using the Any type hint excessively, as it can defeat the purpose of type checking.

By following these guidelines and using type hints effectively, you can improve the quality, readability, and maintainability of your Python code.

3. Checking the Type of Inputs in Python

Checking the type of inputs in Python is a crucial step in ensuring that your functions and programs operate correctly. Python offers several ways to verify the type of a variable, allowing you to handle different data types appropriately.

3.1. Why Check Input Types?

Checking input types is essential for several reasons:

  • Preventing Errors: It helps prevent runtime errors caused by unexpected data types.
  • Ensuring Correct Behavior: It ensures that your functions behave as expected by handling different data types appropriately.
  • Improving Code Reliability: It makes your code more robust and reliable by validating input data.
  • Enhancing Security: It can help prevent security vulnerabilities by ensuring that input data is safe and appropriate.

3.2. Using isinstance() for Type Checking

The isinstance() function is the primary tool for checking the type of an object in Python. It takes two arguments: the object to check and the type to check against.

def check_type(input_var, expected_type):
    if isinstance(input_var, expected_type):
        print(f"Input is of type {expected_type}")
    else:
        print(f"Input is not of type {expected_type}")

check_type("Hello", str)  # Output: Input is of type <class 'str'>
check_type(123, int)    # Output: Input is of type <class 'int'>
check_type(123, str)    # Output: Input is not of type <class 'str'>

This example demonstrates how to use isinstance() to check if a variable is of a specific type.

3.3. Checking for Multiple Types

You can also use isinstance() to check if a variable is one of several different types by passing a tuple of types as the second argument.

def check_multiple_types(input_var):
    if isinstance(input_var, (int, float)):
        print("Input is either an integer or a float")
    else:
        print("Input is not an integer or a float")

check_multiple_types(123)    # Output: Input is either an integer or a float
check_multiple_types(3.14)   # Output: Input is either an integer or a float
check_multiple_types("Hello")  # Output: Input is not an integer or a float

This example shows how to check if a variable is either an integer or a float.

3.4. Type Checking with Type Hints

As discussed earlier, type hints can be used to specify the expected type of a variable or function argument. While type hints are primarily used for static analysis, you can also use them to perform runtime type checking.

from typing import List

def process_names(names: List[str]):
    if not isinstance(names, list):
        raise TypeError("Input must be a list")
    for name in names:
        if not isinstance(name, str):
            raise TypeError("List elements must be strings")
    print("Processing names:", names)

process_names(["John", "Jane", "Mike"])  # Output: Processing names: ['John', 'Jane', 'Mike']

try:
    process_names([1, 2, 3])
except TypeError as e:
    print("Error:", e)  # Output: Error: List elements must be strings

This example uses type hints to specify that the process_names function expects a list of strings. It then uses isinstance() to check that the input is a list and that each element in the list is a string.

3.5. Using Abstract Base Classes (ABCs)

Python’s collections.abc module provides abstract base classes (ABCs) that can be used to check if an object implements a particular interface. For example, you can use Iterable to check if an object is iterable or Sequence to check if an object is a sequence.

from collections.abc import Iterable, Sequence

def check_iterable(input_var):
    if isinstance(input_var, Iterable):
        print("Input is iterable")
    else:
        print("Input is not iterable")

check_iterable([1, 2, 3])  # Output: Input is iterable
check_iterable("Hello")    # Output: Input is iterable
check_iterable(123)      # Output: Input is not iterable

def check_sequence(input_var):
    if isinstance(input_var, Sequence):
        print("Input is a sequence")
    else:
        print("Input is not a sequence")

check_sequence([1, 2, 3])  # Output: Input is a sequence
check_sequence("Hello")    # Output: Input is a sequence
check_sequence({1, 2, 3})  # Output: Input is not a sequence

These examples demonstrate how to use ABCs to check if an object implements a particular interface.

3.6. Example: Validating Input with Custom Classes

You can also use isinstance() to check if an object is an instance of a custom class.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

def process_person(person):
    if isinstance(person, Person):
        print("Processing person:", person.name, person.age)
    else:
        print("Input is not a Person object")

john = Person("John", 30)
process_person(john)  # Output: Processing person: John 30
process_person("Hello") # Output: Input is not a Person object

This example shows how to use isinstance() to check if an object is an instance of the Person class.

3.7. Raising Exceptions for Invalid Types

When an input variable does not match the expected type, it is good practice to raise an exception to signal an error. Python provides several built-in exception types that you can use, such as TypeError and ValueError.

def process_number(number):
    if not isinstance(number, (int, float)):
        raise TypeError("Input must be an integer or a float")
    if number < 0:
        raise ValueError("Input must be a non-negative number")
    print("Processing number:", number)

try:
    process_number(123)
    process_number(-5)
except TypeError as e:
    print("Error:", e)
except ValueError as e:
    print("Error:", e)

This example raises a TypeError if the input is not an integer or a float and a ValueError if the input is a negative number.

3.8. Best Practices for Type Checking

Here are some best practices for type checking in Python:

  • Use isinstance() for Basic Type Checks: Use isinstance() to check if a variable is of a specific type or one of several different types.
  • Use Type Hints for Static Analysis: Use type hints to specify the expected types of variables and function arguments, and use a type checker like mypy to perform static analysis.
  • Use ABCs for Interface Checks: Use abstract base classes to check if an object implements a particular interface.
  • Raise Exceptions for Invalid Types: Raise exceptions to signal an error when an input variable does not match the expected type.
  • Document Your Code: Document your code with clear and concise type information to improve readability and maintainability.

By following these best practices, you can create more robust, reliable, and maintainable Python code.

4. Checking if Inputs Exist in Python

Checking if inputs exist in Python is a fundamental aspect of programming, especially when dealing with user input, file handling, or external data sources. Python provides several ways to verify the existence and validity of inputs, ensuring that your code operates correctly and handles potential errors gracefully.

4.1. Why Check if Inputs Exist?

Checking if inputs exist is crucial for several reasons:

  • Preventing Errors: It helps prevent runtime errors caused by missing or invalid data.
  • Ensuring Correct Behavior: It ensures that your functions behave as expected by handling different input scenarios appropriately.
  • Improving Code Reliability: It makes your code more robust and reliable by validating input data.
  • Enhancing User Experience: It provides meaningful feedback to users when they provide invalid or missing input.

4.2. Checking for None in Python

In Python, None is a special value that represents the absence of a value or a null value. Checking for None is a common way to determine if an input exists.

def check_none(input_var):
    if input_var is None:
        print("Input is None")
    else:
        print("Input is not None")

check_none(None)    # Output: Input is None
check_none("Hello") # Output: Input is not None
check_none(123)     # Output: Input is not None

This example demonstrates how to use is None to check if a variable is None.

4.3. Checking for Empty Strings

An empty string is a string that contains no characters (i.e., ""). Checking for empty strings is important when dealing with text-based input.

def check_empty_string(input_str):
    if input_str == "":
        print("Input is an empty string")
    else:
        print("Input is not an empty string")

check_empty_string("")      # Output: Input is an empty string
check_empty_string("Hello") # Output: Input is not an empty string

This example shows how to check if a string is empty.

4.4. Checking for Empty Lists, Tuples, and Dictionaries

Empty lists, tuples, and dictionaries are collections that contain no elements. Checking for empty collections is important when dealing with data structures.

def check_empty_list(input_list):
    if len(input_list) == 0:
        print("Input is an empty list")
    else:
        print("Input is not an empty list")

check_empty_list([])      # Output: Input is an empty list
check_empty_list([1, 2, 3]) # Output: Input is not an empty list

def check_empty_tuple(input_tuple):
    if len(input_tuple) == 0:
        print("Input is an empty tuple")
    else:
        print("Input is not an empty tuple")

check_empty_tuple(())      # Output: Input is an empty tuple
check_empty_tuple((1, 2, 3)) # Output: Input is not an empty tuple

def check_empty_dict(input_dict):
    if len(input_dict) == 0:
        print("Input is an empty dictionary")
    else:
        print("Input is not an empty dictionary")

check_empty_dict({})      # Output: Input is an empty dictionary
check_empty_dict({"a": 1, "b": 2}) # Output: Input is not an empty dictionary

These examples demonstrate how to check if a list, tuple, or dictionary is empty using the len() function.

4.5. Using None as a Default Value

Using None as a default value for function arguments is a common practice in Python. It allows you to indicate that an argument is optional and can be omitted by the caller.

def greet(name=None):
    if name is None:
        print("Hello, stranger!")
    else:
        print(f"Hello, {name}!")

greet()         # Output: Hello, stranger!
greet("John")    # Output: Hello, John!

In this example, the name argument has a default value of None. If the caller does not provide a value for name, the function will print “Hello, stranger!”.

4.6. Avoiding None and Using Default Values

While using None as a default value is common, some developers prefer to avoid it altogether and use other default values instead. This can help avoid potential errors caused by unexpected None values.

def process_names(names=[]):
    if not names:
        print("No names provided")
    else:
        print("Processing names:", names)

process_names()         # Output: No names provided
process_names(["John", "Jane"]) # Output: Processing names: ['John', 'Jane']

In this example, the names argument has a default value of [] (an empty list). If the caller does not provide a value for names, the function will print “No names provided”.

4.7. Checking for File Existence

When working with files, it is important to check if a file exists before attempting to open or read from it. You can use the os.path.exists() function to check if a file exists.

import os

def check_file_exists(file_path):
    if os.path.exists(file_path):
        print("File exists")
    else:
        print("File does not exist")

check_file_exists("my_file.txt") # Output: File does not exist (if the file does not exist)

This example demonstrates how to use os.path.exists() to check if a file exists.

4.8. Handling Missing Input from User

When prompting users for input, it is important to handle the case where the user does not provide any input. You can check if the input is an empty string and prompt the user to enter the input again.

def get_user_input():
    while True:
        user_input = input("Enter your name: ")
        if user_input == "":
            print("Please enter your name")
        else:
            return user_input

name = get_user_input()
print("Hello,", name)

This example prompts the user to enter their name and checks if the input is an empty string. If the input is empty, it prompts the user to enter their name again until a valid input is provided.

4.9. Best Practices for Checking Input Existence

Here are some best practices for checking input existence in Python:

  • Check for None When Appropriate: Use is None to check if a variable is None when None is a valid or expected value.
  • Check for Empty Strings: Check for empty strings when dealing with text-based input.
  • Check for Empty Collections: Check for empty lists, tuples, and dictionaries when dealing with data structures.
  • Use Default Values: Use default values for function arguments to indicate that an argument is optional.
  • Check for File Existence: Check if a file exists before attempting to open or read from it.
  • Handle Missing User Input: Handle the case where the user does not provide any input and prompt them to enter the input again.
  • Document Your Code: Document your code with clear and concise information about how inputs are checked and handled to improve readability and maintainability.

By following these best practices, you can create more robust, reliable, and user-friendly Python code.

5. Using assert Statements for Type Checking

The assert statement in Python is a debugging aid that tests a condition. If the condition is true, the program continues to execute. If the condition is false, an AssertionError exception is raised. While assert statements can be used for type checking, it’s important to understand their purpose and limitations.

5.1. What is an assert Statement?

An assert statement has the following syntax:

assert condition, message

If condition is true, nothing happens. If condition is false, an AssertionError is raised with the optional message.

5.2. Using assert for Type Checking

You can use assert statements to check the type of a variable:

def process_data(data):
    assert isinstance(data, (int, float)), "Data must be an integer or a float"
    print("Processing data:", data)

process_data(123)   # Output: Processing data: 123
process_data(3.14)  # Output: Processing data: 3.14

try:
    process_data("Hello")
except AssertionError as e:
    print("Error:", e)  # Output: Error: Data must be an integer or a float

This example uses an assert statement to check if the input data is an integer or a float. If it is not, an AssertionError is raised with a descriptive message.

5.3. Limitations of assert Statements

assert statements are primarily intended for debugging and testing purposes. They are not meant to be used for general-purpose error handling in production code. Here are some limitations of assert statements:

  • Disabled in Optimized Mode: When Python is run in optimized mode (using the -O or -OO flags), assert statements are disabled and have no effect. This means that the type checks will not be performed in production if the code is run in optimized mode.
  • Not for User Errors: assert statements should not be used to handle user errors or invalid input. They are intended for detecting internal errors and inconsistencies in the code.
  • Abrupt Termination: When an AssertionError is raised, it typically results in the abrupt termination of the program, which may not be desirable in a production environment.

5.4. Alternatives to assert for Production Code

For production code, it is generally better to use more robust error handling mechanisms, such as raising exceptions or using conditional statements to validate input.

def process_data(data):
    if not isinstance(data, (int, float)):
        raise TypeError("Data must be an integer or a float")
    print("Processing data:", data)

process_data(123)   # Output: Processing data: 123
process_data(3.14)  # Output: Processing data: 3.14

try:
    process_data("Hello")
except TypeError as e:
    print("Error:", e)  # Output: Error: Data must be an integer or a float

This example uses a conditional statement and a TypeError exception to handle invalid input, which is a more appropriate approach for production code.

5.5. When to Use assert Statements

Despite their limitations, assert statements can be useful in certain situations:

  • Debugging: Use assert statements to check for internal errors and inconsistencies during development and testing.
  • Testing: Use assert statements in unit tests to verify that your code behaves as expected.
  • Internal Checks: Use assert statements to enforce preconditions and postconditions in your code.

5.6. Example: Using assert for Preconditions

A precondition is a condition that must be true before a function is called. You can use assert statements to enforce preconditions:

def calculate_square_root(number):
    assert isinstance(number, (int, float)), "Number must be an integer or a float"
    assert number >= 0, "Number must be non-negative"
    return number ** 0.5

try:
    result = calculate_square_root(25)
    print("Square root:", result)  # Output: Square root: 5.0

    result = calculate_square_root(-5)
except AssertionError as e:
    print("Error:", e)  # Output: Error: Number must be non-negative

This example uses assert statements to enforce that the input number is an integer or a float and that it is non-negative.

5.7. Example: Using assert for Postconditions

A postcondition is a condition that must be true after a function is called. You can use assert statements to verify postconditions:

def calculate_discount(price, discount_percentage):
    assert isinstance(price, (int, float)), "Price must be an integer or a float"
    assert isinstance(discount_percentage, (int, float)), "Discount percentage must be an integer or a float"
    assert 0 <= discount_percentage <= 100, "Discount percentage must be between 0 and 100"

    discounted_price = price * (1 - discount_percentage / 100)
    assert discounted_price <= price, "Discounted price cannot be greater than original price"
    return discounted_price

try:
    final_price = calculate_discount(100, 20)
    print("Final price:", final_price)  # Output: Final price: 80.0

    final_price = calculate_discount(100, 120)
except AssertionError as e:
    print("Error:", e)  # Output: Error: Discount percentage must be between 0 and 100

This example uses an assert statement to verify that the discounted price is not greater than the original price.

5.8. Best Practices for Using assert Statements

Here are some best practices for using assert statements in Python:

  • Use for Debugging and Testing: Use assert statements primarily for debugging and testing purposes.
  • Enforce Preconditions and Postconditions: Use assert statements to enforce preconditions and postconditions in your code.
  • Provide Descriptive Messages: Provide descriptive messages in your assert statements to help identify the cause of the error.
  • Do Not Use for User Errors: Do not use assert statements to handle user errors or invalid input.
  • Use Robust Error Handling in Production: Use more robust error handling mechanisms, such as raising exceptions or using conditional statements, in production code.

By following these best practices, you can use assert statements effectively to improve the quality and reliability of your Python code.

6. Checking for a List of Strings in Python

When working with lists in Python, it’s often necessary to ensure that the list contains elements of a specific type, such as strings. Verifying that a list contains only strings is crucial for maintaining data integrity and ensuring that your code operates correctly.

6.1. Why Check for a List of Strings?

Checking if a list contains only strings is important for several reasons:

  • Preventing Errors: It helps prevent runtime errors caused by unexpected data types in the list.
  • Ensuring Correct Behavior: It ensures that your functions behave as expected by handling lists of strings appropriately.
  • Improving Code Reliability: It makes your code more robust and reliable by validating the contents of the list.
  • Data Integrity: It ensures that the list contains only string data, which is essential for certain operations and algorithms.

6.2. Basic Approach: Looping Through the List

The most straightforward way to check if a list contains only strings is to loop through the list and check the type of each element using the isinstance() function.

def check_list_of_strings(input_list):
    if not isinstance(input_list, list):
        raise TypeError("Input must be a list")
    for element in input_list:
        if not isinstance(element, str):
            raise TypeError("List elements must be strings")
    return True

names = ["John", "Jane", "Mike"]
result = check_list_of_strings(names)
print("Is list of strings:", result)  # Output: Is list of strings: True

mixed_list = ["John", 123, "Mike"]
try:
    result = check_list_of_strings(mixed_list)
except TypeError as e:
    print("Error:", e)  # Output: Error: List elements must be strings

This example defines a function check_list_of_strings that takes a list as input and loops through each element, checking if it is a string. If

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *