Write a python program to filter integer, float, string from a list

1. Introduction

In this blog post, we'll dive into a Python program designed to filter integers, floats, and strings from a mixed list. This task is an excellent way to understand data type checking and list comprehensions in Python, which are powerful tools for data processing and manipulation.

2. Program Steps

1. Create separate lists to hold integers, floats, and strings.

2. Iterate over each element in the mixed list.

3. Check the data type of each element and add it to the corresponding list.

3. Code Program

def filter_list_elements(mixed_list):
    # Step 1: Create separate lists for integers, floats, and strings
    integers = []
    floats = []
    strings = []

    # Step 2 & 3: Iterate and filter elements based on their data type
    for element in mixed_list:
        if isinstance(element, int):
            integers.append(element)
        elif isinstance(element, float):
            floats.append(element)
        elif isinstance(element, str):
            strings.append(element)

    return integers, floats, strings

# Example usage
mixed_list = [1, 2.5, "hello", 3, "world", 4.8]
integers, floats, strings = filter_list_elements(mixed_list)
print(f"Integers: {integers}, Floats: {floats}, Strings: {strings}")

Output:

For the mixed list [1, 2.5, "hello", 3, "world", 4.8], the output will be:
- Integers: [1, 3]
- Floats: [2.5, 4.8]
- Strings: ["hello", "world"]

Explanation:

1. Separate lists (integers, floats, strings) are created to hold elements of each data type. This organization facilitates the sorting of elements based on their type.

2. The program iterates over each element in the mixed_list. Using a for loop, it goes through each element one by one.

3. The isinstance() function checks the data type of each element. Based on the type, the element is appended to the corresponding list. isinstance(element, int) checks for integers, isinstance(element, float) for floats, and isinstance(element, str) for strings.

This approach effectively segregates different data types into separate lists, showcasing the versatility of list comprehensions and type checking in Python.


Comments