How to Concatenate a List Multiple Times in Python?

Estimated read time 2 min read

To concatenate a list multiple times in Python, you can use either list multiplication or list concatenation with a loop. Here are examples of both approaches:

  1. Using list multiplication:
my_list = [1, 2, 3]
concatenated_list = my_list * 3
print(concatenated_list)

In this example, the list my_list is multiplied by the desired number of repetitions (in this case, 3) using the * operator. The resulting list is stored in the concatenated_list variable and then printed.

  1. Using list concatenation with a loop:
my_list = [1, 2, 3]
repetitions = 3
concatenated_list = []
for _ in range(repetitions):
    concatenated_list += my_list
print(concatenated_list)

In this approach, a for loop is used to iterate the desired number of repetitions. In each iteration, the original list my_list is concatenated with the += operator to the concatenated_list variable. The resulting list is stored in concatenated_list and then printed.

Both methods achieve the same result of concatenating a list multiple times. The list multiplication approach is more concise and preferred when the number of repetitions is known in advance. The list concatenation with a loop approach provides more flexibility and can be used when the number of repetitions is variable or needs to be determined dynamically.

Choose the method that best suits your requirements and the complexity of the task at hand.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply