Create a list with same value repeated N times in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
4 min

banner

# Table of Contents

  1. Create a list with same value repeated N times in Python
  2. Create a list with same value repeated N times using itertools.repeat()
  3. Append an item to a list N times using list.extend()

# Create a list with same value repeated N times in Python

Use the multiplication operator to create a list with the same value repeated N times in Python, e.g. my_list = ['abc'] * 3.

The result of the expression will be a new list that contains the specified value N times.

main.py
my_list = ['abc'] * 3 print(my_list) # ๐Ÿ‘‰๏ธ ['abc', 'abc', 'abc']

create list with same value repeated n times

The item you specify in the list will be contained N times in the new list the operation returns.

Make sure to wrap the value you want to repeat in a list.

One thing to be aware of is - if you use this approach with mutable containers like a list or a dictionary, they all point to the same location in memory and have the same reference.
main.py
result = [[]] * 3 # ๐Ÿ‘‡๏ธ [[], [], []] print(result) result[0].append('a') # ๐Ÿ‘‡๏ธ [['a'], ['a'], ['a']] print(result)

We created a list that contains 3 nested lists. However, note that adding an item to one of the lists, added the item in all 3.

This is because all of the nested lists point to the same location in memory.

# Using a list comprehension to resolve the issue

One way to avoid this issue is to use a list comprehension.

main.py
result = [[] for i in range(0, 3)] # ๐Ÿ‘‡๏ธ [[], [], []] print(result) result[0].append('a') # ๐Ÿ‘‡๏ธ [['a'], [], []] print(result)

using list comprehension to resolve the issue

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

The range() class is commonly used for looping a specific number of times in for loops and takes the following parameters:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

If you only pass a single argument to the range() constructor, it is considered to be the value for the stop parameter.

You can also specify items in the list, just like we did in the first example, and we still end up creating a list with 3 distinct nested lists.

main.py
result = [['a'] for i in range(0, 3)] # ๐Ÿ‘‡๏ธ [['a'], ['a'], ['a']] print(result) result[0].append('b') # ๐Ÿ‘‡๏ธ [['a', 'b'], ['a'], ['a']] print(result)

You can also use the itertools.repeat() method to create a list that contains the same item N times.

# Create a list with the same values repeated N times using a for loop

If you need to create a list by repeating multiple values N times, use a for loop.

main.py
a_list = [1, 2, 3] new_list = [] count = 3 for index in range(count): for item in a_list: new_list.append(item) # ๐Ÿ‘‡๏ธ [1, 2, 3, 1, 2, 3, 1, 2, 3] print(new_list)

create list with same value repeated n times using for loop

We used a for loop to iterate over a range object 3 times.

On each iteration, we use a nested for loop to iterate over the list and add its values to the new list using append().

# Create a list with same value repeated N times using itertools.repeat()

This is a three-step process:

  1. Import the itertools module.
  2. Call the repeat() method, e.g. itertools.repeat('a', 3).
  3. Use the list() class to convert the object to a list.
main.py
import itertools my_list = list(itertools.repeat('a', 3)) print(my_list) # ๐Ÿ‘‰๏ธ ['a', 'a', 'a']

create list with same value repeated n times using itertools

The itertools.repeat() method is used to make an iterator that returns the provided object N times.

The method takes the following 2 arguments:

NameDescription
objectThe object to be returned from the iterator
timesHow many times the object should get returned from the iterator (optional)

If you don't provide a value for the times argument, the iterator runs indefinitely.

Note that this approach also suffers from the same issue when trying to create a list of mutable objects.

main.py
import itertools my_list = list(itertools.repeat(['a'], 3)) print(my_list) # ๐Ÿ‘‰๏ธ [['a'], ['a'], ['a']] my_list[0].append('b') print(my_list) # ๐Ÿ‘‰๏ธ [['a', 'b'], ['a', 'b'], ['a', 'b']]

You can use a list comprehension to avoid this.

main.py
my_list = [['a'] for i in range(0, 3)] print(my_list) # ๐Ÿ‘‰๏ธ [['a'], ['a'], ['a']] my_list[0].append('b') print(my_list) # ๐Ÿ‘‰๏ธ [['a', 'b'], ['a'], ['a']]

All of the nested lists we created point to a different location in memory, so updating one doesn't mutate the others.

# Append an item to a list N times using list.extend()

If you need to append an item to a list N times:

  1. Use a generator expression to iterate over a range object.
  2. Use the list.extend() method to extend the original list with the value repeated N times.
main.py
my_list = ['a', 'b'] my_list.extend('c' for _ in range(3)) print(my_list) # ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'c', 'c']

We used a generator expression to iterate over the range object.

Generator expressions are very similar to list comprehensions.

They are used to perform some operation for every element or select a subset of elements that meet a condition.

The list.extend() method takes an iterable and extends the list by appending all of the items from the iterable.

main.py
my_list = ['bobby'] my_list.extend(['hadz', '.', 'com']) print(my_list) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz', '.', 'com']

The list.extend method returns None as it mutates the original list.

This approach is useful when you need to append an item N times to an existing list.

The multiplication operator should be your preferred approach if you need to create a list that contains the same value repeated N times.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev