Element repetition in list in Python


There are scenarios when we need to repeat the values in a list. This duplication of values can be achived in python in the following ways.

Using nested for loop

It is a straight forward approach in which pick each element, take through a inner for loop to create its duplicate and then pass both of them to an outer for loop.

Example

 Live Demo

# Given list
listA = ['Mon', 'Tue', 9, 3, 3]

print("Given list : ",listA)

# Adding another element for each element
Newlist = [i for i in listA for n in (0, 1)]

# Result
print("New list after duplication: ",Newlist)

Output

Running the above code gives us the following result −

Given list : ['Mon', 'Tue', 9, 3, 3]
New list after duplication: ['Mon', 'Mon', 'Tue', 'Tue', 9, 9, 3, 3, 3, 3]

Using itertools

The itertools module deals with data manipulation in iterables. Here we apply the chain.from_iterables which

Example

 Live Demo

import itertools

# Given list
listA = ['Mon', 'Tue', 9, 3, 3]

print("Given list : ",listA)

# Adding another element for each element
Newlist = list(itertools.chain.from_iterable([n, n] for n in listA))

# Result
print("New list after duplication: ",Newlist)

Output

Running the above code gives us the following result −

Given list : ['Mon', 'Tue', 9, 3, 3]
New list after duplication: ['Mon', 'Mon', 'Tue', 'Tue', 9, 9, 3, 3, 3, 3]

With reduce

The reduce function applies a particular function passed to it as an argument to all of the list elements passed onto it as second argument. We use this with add function which adds the duplicate element of each element present in the list.

Example

 Live Demo

from functools import reduce
from operator import add

# Given list
listA = ['Mon', 'Tue', 9, 3, 3]

print("Given list : ",listA)

# Adding another element for each element
Newlist = list(reduce(add, [(i, i) for i in listA]))

# Result
print("New list after duplication: ",Newlist)

Output

Running the above code gives us the following result −

Given list : ['Mon', 'Tue', 9, 3, 3]
New list after duplication: ['Mon', 'Mon', 'Tue', 'Tue', 9, 9, 3, 3, 3, 3]

Updated on: 05-May-2020

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements