Python | Increase list size by padding each element by N

Given a list and an integer N, write a Python program to increase the size of the list by padding each element by N.

Examples:

Input : lst = [1, 2, 3]
        N = 3
Output : [1, 1, 1, 2, 2, 2, 3, 3, 3]

Input : lst = ['cats', 'dogs']
        N = 2
Output : ['cats', 'cats', 'dogs', 'dogs']

Approach #1 : List comprehension



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to increase list size 
# by padding each element by N
  
def increaseSize(lst, N):
      
    return [el for el in lst for _ in range(N)]
          
# Driver code
lst = [1, 2, 3]
N = 3
print(increaseSize(lst, N))

chevron_right


Output:

[1, 1, 1, 2, 2, 2, 3, 3, 3]

 
Approach #2 : Using functools.reduce() method

The reduce function apply a particular function passed in its argument to all of the list elements. Therefore, in this approach we apply a function on each element where it’s occurrence gets multiplied by N.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to increase list size 
# by padding each element by N
from functools import reduce
  
def increaseSize(lst, N):
      
    return reduce(lambda x, y: x + y, [[el]*N for el in lst])
          
# Driver code
lst = [1, 2, 3]
N = 3
print(increaseSize(lst, N))

chevron_right


Output:

[1, 1, 1, 2, 2, 2, 3, 3, 3]

 
Approach #3 : Using itertools.chain()

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to increase list size 
# by padding each element by N
from itertools import chain
  
def increaseSize(lst, N):
      
    return list(chain(*([el]*N for el in lst)))
          
# Driver code
lst = [1, 2, 3]
N = 3
print(increaseSize(lst, N))

chevron_right


Output:

[1, 1, 1, 2, 2, 2, 3, 3, 3]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.