Python | Retain records of specific length

Python | Retain records of specific length

Filtering records based on specific lengths is a common task, especially in data processing workflows. This tutorial will explain how to retain records of specific length in Python.

Problem Statement:

Given a list of strings (records), we want to retain only those records that have a specified length.

Example:

For the list ["apple", "banana", "kiwi", "grapes"] and desired length 5, the result should be ["apple", "grapes"].

Tutorial:

  • Using List Comprehension:

Python's list comprehensions are an efficient way to filter lists. We can use this feature to filter records based on their lengths.

def retain_records_of_length(records, length):
    return [record for record in records if len(record) == length]

# Example usage:
records = ["apple", "banana", "kiwi", "grapes"]
desired_length = 5
print(retain_records_of_length(records, desired_length))  # Output: ['apple', 'grapes']
  • Using the filter() Function:

The filter() function can be used to filter a list based on a condition. It returns an iterator which can be converted to a list using list().

def retain_records_of_length(records, length):
    return list(filter(lambda record: len(record) == length, records))

# Example usage:
records = ["apple", "banana", "kiwi", "grapes"]
desired_length = 5
print(retain_records_of_length(records, desired_length))  # Output: ['apple', 'grapes']
  • Using a Loop:

For those who want an explicit approach, loops can be used to iterate over the list and retain records with the desired length.

def retain_records_of_length(records, length):
    result = []
    for record in records:
        if len(record) == length:
            result.append(record)
    return result

# Example usage:
records = ["apple", "banana", "kiwi", "grapes"]
desired_length = 5
print(retain_records_of_length(records, desired_length))  # Output: ['apple', 'grapes']

Edge Case:

What if the desired length is provided as a list of valid lengths, and we want to retain records that match any of those lengths?

For example, given the list ["apple", "kiwi", "grapes"] and desired lengths [4, 6], the result should be ["kiwi", "grapes"].

Here's a solution using list comprehension:

def retain_records_of_lengths(records, lengths):
    return [record for record in records if len(record) in lengths]

# Example usage:
records = ["apple", "kiwi", "grapes"]
desired_lengths = [4, 6]
print(retain_records_of_lengths(records, desired_lengths))  # Output: ['kiwi', 'grapes']

Conclusion:

In this tutorial, we explored various methods to filter records based on their length in Python. Depending on your preference, you can opt for the concise list comprehension, the functional filter(), or the more verbose loop method.


More Tags

left-join flask-restful django-userena fnmatch hashset scanf database-normalization mockito nsarray database

More Programming Guides

Other Guides

More Programming Examples