Open In App

Python | Increase list size by padding each element by N

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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 

Python3




# 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))


Output:

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

Time Complexity: O(n), where n is the number of elements in the list 
Auxiliary Space: O(1), constant space needed

  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. 

Python3




# 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))


Output:

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

  Approach #3 : Using itertools.chain() 

Python3




# 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))


Output:

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

Approach #4 : Using * and extend() method

  1. Initiate a for loop to access list elements
  2. Repeat each list element by using * operator
  3. And add repeated elements to output list(using extend())
  4. Display output list

Python3




# Python3 program to increase list size
# by padding each element by N
 
lst = [1, 2, 3]
N = 3
x=[]
for i in lst:
    x.extend([i]*N)
print(x)


Output

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

Time Complexity : O(N)

Auxiliary Space : O(N)



Last Updated : 17 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads