0
0
Pythonprogramming~5 mins

List concatenation and repetition in Python

Choose your learning style9 modes available
Introduction
List concatenation and repetition help you combine lists or repeat their items easily, just like joining or copying groups of things in real life.
When you want to join two lists of groceries into one big list.
When you need to repeat a list of tasks multiple times.
When creating a pattern by repeating a list of colors.
When merging guest lists from two events.
When you want to duplicate a list of default settings.
Syntax
Python
list1 + list2  # Concatenates two lists
list * n       # Repeats the list n times
The + operator joins two lists into a new list without changing the originals.
The * operator repeats the list items n times, creating a new list.
Examples
Concatenates two lists of fruits into one list.
Python
fruits = ['apple', 'banana']
more_fruits = ['orange', 'grape']
all_fruits = fruits + more_fruits
print(all_fruits)
Repeats the list of numbers three times.
Python
numbers = [1, 2, 3]
repeated_numbers = numbers * 3
print(repeated_numbers)
Concatenating an empty list with another list returns the other list.
Python
empty_list = []
result = empty_list + [1, 2]
print(result)
Repeating a list with one item multiple times.
Python
single_item = [5]
repeated_single = single_item * 4
print(repeated_single)
Sample Program
This program shows how to join two lists of fruits and how to repeat a list of numbers multiple times.
Python
fruits = ['apple', 'banana']
more_fruits = ['orange', 'grape']
print('Before concatenation:', fruits)
print('Second list:', more_fruits)
all_fruits = fruits + more_fruits
print('After concatenation:', all_fruits)

numbers = [1, 2, 3]
print('Original numbers:', numbers)
repeated_numbers = numbers * 3
print('After repetition:', repeated_numbers)
OutputSuccess
Important Notes
Concatenation (+) creates a new list and does not change the original lists.
Repetition (*) also creates a new list; the original list stays the same.
Both operations have time complexity proportional to the size of the resulting list.
Avoid using repetition with very large numbers to prevent memory issues.
Use concatenation when you want to combine lists; use repetition when you want to duplicate list items.
Summary
Use + to join two lists into one bigger list.
Use * to repeat the items in a list multiple times.
Both create new lists and do not change the original lists.