Python | Sum two unequal length lists in cyclic manner

Python | Sum two unequal length lists in cyclic manner

In this tutorial, you'll learn how to sum two lists of unequal lengths in a cyclic manner. This means that if one list is shorter than the other, its elements will be reused in cycles until both lists have been entirely processed.

Example:

Suppose you have the following lists:

list1 = [1, 2, 3]
list2 = [1, 2, 3, 4, 5, 6]

You want to compute the cyclic summation of these lists, which would be:

1 + 1 = 2, 2 + 2 = 4, 3 + 3 = 6, 1 + 4 = 5, 2 + 5 = 7, 3 + 6 = 9

The resultant list would be:

result = [2, 4, 6, 5, 7, 9]

Step by Step Tutorial:

  • Understanding the Problem:

    • You have two lists of possibly unequal lengths.
    • Your goal is to sum these lists in a cyclic manner.
  • Using Python's itertools.cycle and zip:

    • itertools.cycle allows us to cycle through a list infinitely.
    • zip is used to pair elements from two lists together. If the lists are of unequal lengths, zip will stop at the shortest list. However, by cycling the shorter list, we can achieve the desired behavior.

Here's how you can do it:

from itertools import cycle

result = [a + b for a, b in zip(cycle(list1), list2)]
  • Display the Result:
print(result)

Full Code:

from itertools import cycle

list1 = [1, 2, 3]
list2 = [1, 2, 3, 4, 5, 6]

# Summation of lists in a cyclic manner
result = [a + b for a, b in zip(cycle(list1), list2)]

# Print the result
print(result)  # Output: [2, 4, 6, 5, 7, 9]

Considerations:

  • Ensure that both lists contain only elements that support the addition operation (like numbers).
  • While itertools.cycle creates an infinite cycle, using zip with another finite iterator (like our list) ensures that the process will eventually stop.
  • This approach is concise and leverages Python's powerful standard library for efficient execution.

And that's how you compute the cyclic summation of two lists of possibly unequal lengths in Python!


More Tags

payment canoe flicker uitabbarcontroller class-validator data-analysis listener heap-memory picturebox git-clone

More Programming Guides

Other Guides

More Programming Examples