Blogging, Resources, Tools, Training

Total: 0,00

Blogging, Resources, Tools, Training

Total: 0,00

# Create List of single item repeated N times in Python

In this article, we will learn different ways to create a list of single item repeated N times in Python.

## Method 1: Using Astrik

We can create a list object with one element only, and then multiply that list object with N. It will repeat the single element of list N times, and returns a list of N repeated elements. Let’s see an example,

```N = 7

# Create a List of N repeated numbers i.e.
# seven times 22 in this case
listOfNumbers =  * N

print(listOfNumbers)
```

Output:

```[22, 22, 22, 22, 22, 22, 22]
```

It created a list of 7 repeated elements i.e. number 22 repeated seven times.

## Method 2: Using List comprehension

We can iterate over a range of numbers i.e. from 0 to N. In each iteration, add same element into the list. In the end, list comprehension will give us a list of N repeated elements. Let’s see an example, where we will create a list of 7 elements.

```N = 7

# Create a List of N repeated numbers i.e.
# seven times 22 in this case
listOfNumbers = [22 for i in range(N)]

print(listOfNumbers)
```

Output:

```[22, 22, 22, 22, 22, 22, 22]
```

It created a list of 7 repeated elements i.e. number 22 repeated seven times.

## Method 3: Using itertools

The itertools module, provides a function repeat(), almost exactly for this purpose. The function accepts an element, and a repeation count as arguments. It yields the object for the specified number of times. We can use this to create a list of N repeated items. For that, we need to pass th element and repeation count N as arguments in the itertools.repeat() function. Then store the returned values to a list. Let’s see an example,

### Best Resources to Learn Python:

```import itertools

N = 7

# Create a List of N repeated numbers i.e.
# seven times 22 in this case
listOfNumbers = list(itertools.repeat(22, N))

print(listOfNumbers)
```

Output:

```[22, 22, 22, 22, 22, 22, 22]
```

It created a list of 7 repeated elements i.e. number 22 repeated seven times.

## Summary

We learned how to create a list of N repeated items in Python. Thanks.