Open In App

Python | Optional padding in list elements

Improve
Improve
Like Article
Like
Save
Share
Report

In real-world problems, we sometimes require to pad the element of the list according to a condition that the maximum characters have reached. Padding a number with 0 if it’s length is less than required by any field is one of the basic issues that occur in web forms in Web Development. Let’s discuss certain ways in which this issue can be solved. 

Method #1: Using list comprehension 

This problem can be solved easily using the basic list comprehension in which we just need to use string formatting to perform the optional padding with 0 if size of each element is less than the specified size. 

Python3




# Python3 code to demonstrate
# to perform list element padding
# using list comprehension
 
# initializing list
test_list = [3, 54, 4, 1, 10]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using list comprehension
# to perform list element padding
res = ["%02d" % i for i in test_list]
 
# printing result
print("The list after element padding " + str(res))


Output

The original list is : [3, 54, 4, 1, 10]
The list after element padding ['03', '54', '04', '01', '10']

Time Complexity: O(n), where n is the number of elements in the list.
Auxiliary Space: O(n), where n is the number of elements in the result list.

Method #2 : Using str.rjust()

There is a function dedicated in python to do this job. rjust() function does the task of specifying the size of the string and also takes the character in which the character has to be padded. 

Python3




# Python3 code to demonstrate
# to perform list element padding
# using str.rjust()
 
# initializing list
test_list = [3, 54, 4, 1, 10]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using str.rjust()
# to perform list element padding
res = [str(i).rjust(2, '0') for i in test_list]
 
# printing result
print("The list after element padding " + str(res))


Output

The original list is : [3, 54, 4, 1, 10]
The list after element padding ['03', '54', '04', '01', '10']

Time complexity: O(n), where n is the length of the list “test_list”.
Auxiliary space: O(n), where n is the length of the list “res”.

Method #3 : Using max() , len() and str() methods

Python3




# Python3 code to demonstrate
# to perform list element padding
 
# initializing list
test_list = [3, 54, 4, 1, 10]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using list comprehension
# to perform list element padding
a = max(test_list)
b = len(str(a))
 
# Empty dictionary
res = []
 
for i in test_list:
    c = len(str(i))
    if(c != b):
        x = "0"*(b-c)+str(i)
        res.append(x)
    else:
        res.append(str(i))
 
# Printing result
print("The list after element padding " + str(res))


Output

The original list is : [3, 54, 4, 1, 10]
The list after element padding ['03', '54', '04', '01', '10']

Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), as an additional list res is created to store the padded elements. 

Method #4 : Using map() and rjust():

Python3




# Initialize the list
test_list = [3, 54, 4, 1, 10]
# Print the original list
print("The original list is:", test_list)
# Use the map() function to apply the format() function to each element of the list
result = list(map("{:02d}".format, test_list))
# Print the result
print("The padded list is:", result)
#This code is contributed by Jyothi pinjala.


Output

The original list is: [3, 54, 4, 1, 10]
The padded list is: ['03', '54', '04', '01', '10']

Time complexity: O(n)
Auxiliary Space: O(n)

Method #5: Using a for loop to iterate over each element of the list, converting it to a string and padding it with zeros on the left side to a width of 2 using the string method zfill()

Approach:

  1. Create a list of integers to be padded called “test_list“.
  2. Print the original list “test_list“.
  3. Create an empty list called “res“.
  4. Loop through each element in “test_list” using a for loop.
    1. Convert the integer to a string using “str()“.
    2. Use “zfill()” to add leading zeros to the string if it is less than 2 characters long.
    3. Append the padded string to the “res” list.
  5. Print the resulting “res” list.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate
# to perform list element padding
# using for loop
 
# initializing list
test_list = [3, 54, 4, 1, 10]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using for loop
# to perform list element padding
res = []
for i in test_list:
    res.append(str(i).zfill(2))
 
# printing result
print("The list after element padding " + str(res))


Output

The original list is : [3, 54, 4, 1, 10]
The list after element padding ['03', '54', '04', '01', '10']

Time complexity: O(n), where n is the length of the input list. The for loop iterates over each element of the list once.
Auxiliary space: O(n), where n is the length of the input list. The res list stores the result for each element of the input list.

Method #6: Using Numpy’s vectorized string formatting

  1. Import the numpy library.
  2. Convert the test_list to a numpy array using numpy.array().
  3. Use the numpy.core.defchararray.zfill() method to pad each element in the array with leading zeros up to a width of 2.
  4. Convert the resulting array to a list using the tolist() method.
  5. Return the list.

Python3




# Python3 code to demonstrate
# to perform list element padding
# using numpy's vectorized string formatting
 
# Importing numpy library
import numpy as np
 
# Initializing list
test_list = [3, 54, 4, 1, 10]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# using numpy's vectorized string formatting
arr = np.array(test_list)
res = np.core.defchararray.zfill(arr.astype(str), 2).tolist()
 
# Printing result
print("The list after element padding: " + str(res))


Output:

The original list is : [3, 54, 4, 1, 10]
The list after element padding ['03', '54', '04', '01', '10']

Time complexity: O(n)
Auxiliary space: O(n)

Method #7: Using a generator expression and join()

  1. Use a generator expression to convert each integer element of the input list to a zero-padded string of length 2 using the str.zfill() method.
  2. Use the join() method to join the resulting generator expression into a single string separated by commas and surrounded by square brackets.
  3. Print the original list and the resulting padded list as a string.

Python3




# Python3 code to demonstrate
# to perform list element padding
# using a generator expression and join()
 
# initializing list
test_list = [3, 54, 4, 1, 10]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using a generator expression and join()
# to perform list element padding
res = "[" + ", ".join(str(i).zfill(2) for i in test_list) + "]"
 
# printing result
print("The list after element padding " + res)


Output

The original list is : [3, 54, 4, 1, 10]
The list after element padding [03, 54, 04, 01, 10]

Time Complexity: O(n), where n is the length of the input list. The generator expression operates on each element of the input list once.
Auxiliary Space: O(n), where n is the length of the input list. The resulting padded list has the same length as the input list.



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