w3resource

Python: Interleave two given list into another list randomly using map function


Write a Python program to interleave two lists into another list randomly. Use the map() function.

Sample Solution:

Python Code:

# Import the 'random' module
import random

# Define a function named 'randomly_interleave' that takes two lists as input
def randomly_interleave(nums1, nums2):
    # Create a list of iterators using the 'iter' function for each input list
    iterators = [iter(nums1)] * len(nums1) + [iter(nums2)] * len(nums2)
    # Use the 'random.sample' function to randomly select iterators from the list and create a new list of values
    # Use the 'map' function with 'next' to extract the values from the selected iterators
    result = list(map(next, random.sample(iterators, len(nums1) + len(nums2))))
    # Return the result
    return result

# Define two lists 'nums1' and 'nums2'
nums1 = [1, 2, 7, 8, 3, 7]
nums2 = [4, 3, 8, 9, 4, 3, 8, 9]

# Print the original lists
print("Original lists:")
print(nums1)
print(nums2)

# Print a newline for better readability
print("\n")

# Print a message indicating the operation to be performed
print("Interleave two given lists into another list randomly:")

# Print the result of calling the 'randomly_interleave' function with the 'nums1' and 'nums2' lists
print(randomly_interleave(nums1, nums2))

Sample Output:

Original lists:
[1, 2, 7, 8, 3, 7]
[4, 3, 8, 9, 4, 3, 8, 9]

Interleave two given list into another list randomly:
[4, 3, 8, 9, 1, 2, 4, 3, 7, 8, 3, 7, 8, 9]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to count the same pair in two given lists. use map() function.
Next: Write a Python program to split a given dictionary of lists into list of dictionaries using map function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.