How to Copy Items in a List n Times in Python?

Estimated read time 1 min read

To copy items in a list n times in Python, you can use a combination of list comprehension and the * operator. Here’s an example:

def copy_items(list_items, n):
    copied_list = [item for item in list_items for _ in range(n)]
    return copied_list

In the above code, the copy_items function takes two arguments: list_items, which is the original list containing the items you want to copy, and n, which is the number of times you want to copy each item.

The list comprehension [item for item in list_items for _ in range(n)] iterates over each item in list_items and creates a new list that repeats each item n times. The _ is a throwaway variable that is used to iterate n times without actually using the variable.

Here’s an example usage of the copy_items function:

original_list = [1, 2, 3]
copied_list = copy_items(original_list, 3)
print(copied_list)

Output:

[1, 1, 1, 2, 2, 2, 3, 3, 3]

In this example, each item in the original_list is copied 3 times, resulting in the copied_list containing [1, 1, 1, 2, 2, 2, 3, 3, 3].

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply