Python | K length Padding in List
Last Updated :
10 May, 2023
In real world problems, we sometimes require to pad the element of list according to a condition that 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
test_list = [ 3 , 54 , 4 , 100 , 10 ]
print ("The original list is : " + str (test_list))
K = 4
temp = " % 0 " + str (K) + "d"
res = [temp % i for i in test_list]
print ("The list after K size element padding : " + str (res))
|
Output :
The original list is : [3, 54, 4, 100, 10]
The list after K size element padding ['0003', '0054', '0004', '0100', '0010']
Time Complexity: O(n) where n is the number of elements in the in the list “test_list”. The list comprehension is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the in the list “test_list”.
Method #2: Using str.rjust() There is a function dedicated in python to do this job. The 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
test_list = [ 3 , 54 , 4 , 100 , 10 ]
print ("The original list is : " + str (test_list))
K = 4
res = [ str (i).rjust(K, '0' ) for i in test_list]
print ("The list after K size element padding : " + str (res))
|
Output :
The original list is : [3, 54, 4, 100, 10]
The list after K size element padding ['0003', '0054', '0004', '0100', '0010']
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Method #3: Using stringformatting
In this method, we use the f-string syntax to format each element of the original list with leading zeros using the :0{k} specifier. The 0 indicates that we want to pad with zeros, and k is the width of the padded string. Finally, we use a list comprehension to apply this formatting to each element of the original list and create the padded list.
Python3
original_list = [ 3 , 54 , 4 , 100 , 10 ]
k = 4
padded_list = [f "{x:0{k}}" for x in original_list]
print (padded_list)
|
Output
['0003', '0054', '0004', '0100', '0010']
Time complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using numpy library:
Algorithm:
1.Import the numpy library.
2.Define the original list and K value.
3.Convert the original list to a numpy array of strings using the astype() method.
4.Use the np.char.zfill() function to pad each string in the array with zeros to a length of K.
5.Convert the padded numpy array back to a list using the tolist() method.
6.Print the original list and the padded list for comparison.
Python3
import numpy as np
test_list = [ 3 , 54 , 4 , 100 , 10 ]
K = 4
string_array = np.array(test_list).astype( str )
padded_array = np.char.zfill(string_array, K)
padded_list = padded_array.tolist()
print ( "Original List:" , test_list)
print ( "Padded List:" , padded_list)
|
Output:
Original List: [3, 54, 4, 100, 10]
Padded List: ['0003', '0054', '0004', '0100', '0010']
Time complexity:
The conversion of the original list to a numpy array takes O(n) time, where n is the length of the list.
The astype() method also takes O(n) time, since it needs to convert each element of the array to a string.
The np.char.zfill() function takes O(nk) time, where k is the length of the padded strings. Since we are padding each string to a length of K, this operation takes O(nK) time in total.
The tolist() method takes O(n) time, since it needs to convert the numpy array back to a list.
Therefore, the overall time complexity of the code is O(nK).
Auxiliary Space:
The numpy array created in step 3 requires O(nk) space, where k is the length of the padded strings. Since we are padding each string to a length of K, this array takes O(nK) space in total.
The padded list created in step 4 also requires O(nk) space, where k is the length of the padded strings. Therefore, the space complexity of the code is O(nK).
Method #5: Using a for loop and string concatenation: A simple way to pad the numbers with leading zeros is to loop over the list, convert each number to a string, and concatenate “0” characters to the left until the resulting string has the desired length.
Step-by-step approach:
- Initialize an empty list to store the padded numbers.
- Loop over the original list.
- Convert each number to a string.
- Check the length of the resulting string.
- If the length is less than k, concatenate “0” characters to the left until the string has length k.
- Append the padded string to the new list.
Python3
lst = [ 3 , 54 , 4 , 100 , 10 ]
k = 4
padded_lst = []
for num in lst:
num_str = str (num)
while len (num_str) < k:
num_str = "0" + num_str
padded_lst.append(num_str)
print ( "The list after k size element padding:" , padded_lst)
|
Output
The list after k size element padding: ['0003', '0054', '0004', '0100', '0010']
Time complexity: O(nk), where n is the length of the list and k is the desired length of each element.
Auxiliary Space: O(nk), where n is the length of the list and k is the desired length of each element.
Method #6: Using re module
This program takes an input list of integers and pads each integer with leading zeros to a fixed length of 4 digits. The padded integers are then stored in a new list.
Step-by-step approach:
- Define the input list.
- Use a list comprehension to iterate through the input list, convert each integer to a string and pad it with leading zeros using the string format method with format specification of “04”.
- Join the padded integers as a single string.
- Use a regular expression to extract groups of four digits from the padded string using the findall() method.
- Store the extracted groups of four digits in a new list.
- Print the resulting padded list.
Python3
import re
lst = [ 3 , 54 , 4 , 100 , 10 ]
padded_str = ''.join([f "{num:04d}" for num in lst])
padded_lst = re.findall(r '\d{4}' , padded_str)
print ( "The list after K size element padding:" , padded_lst)
|
Output
The list after K size element padding: ['0003', '0054', '0004', '0100', '0010']
Time Complexity: O(n), The time complexity of the program is linear with respect to the number of integers in the input list, n. This is because the program performs a constant number of operations for each integer in the list.
Auxiliary Space: O(n), The space complexity of the program is also linear with respect to the number of integers in the input list, n. This is because the program creates a new list of padded integers of length n, and a string of length 4n to store the joined padded integers.
Method 7: Using the zfill() method
Step-by-step approach:
- Initialize the input list, test_list, and K (the number of digits to be padded) as follows:
- Create an empty list res to store the output.
- Loop through each element i of test_list using a for loop and apply the zfill() method to convert it into a string of K digits with leading zeroes.
- Append the resulting string to the res list using the append() method.
- Print the original list and the padded list using the str.join() method to convert the list elements into strings and concatenate them.
Python3
test_list = [ 3 , 54 , 4 , 100 , 10 ]
print ( "The original list is : " + str (test_list))
K = 4
res = []
for i in test_list:
res.append( str (i).zfill(K))
print ( "The list after K size element padding : " + ' ' .join(res))
|
Output
The original list is : [3, 54, 4, 100, 10]
The list after K size element padding : 0003 0054 0004 0100 0010
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list (used to store the output list).
Similar Reads
Python - Optional padding in list elements
Optional padding in list elements involves adding extra elements, such as zeros or placeholders, to a list to ensure it reaches a desired length. This technique is useful when working with fixed-size data structures or when aligning data in lists. Using List ComprehensionThis method pads each elemen
2 min read
Python - Elements Lengths in List
Sometimes, while working with Python lists, can have problem in which we need to count the sizes of elements that are part of lists. This is because list can allow different element types to be its members. This kind of problem can have application in many domains such has day-day programming and we
6 min read
Python | Row lengths in Matrix
The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the lengths of rows of matrix in uneven sized matrix. Let's discuss certain ways in which this problem can be solved. Method #1 : Using max() + m
4 min read
Python - K length decimal Places
In Python, controlling the number of decimal places in your numeric values is essential for presenting results accurately and efficiently. This article explores techniques to manage K-length decimal places in Python. Given a Decimal Number, extend its digits to K length. Input: num = 76.8, K = 5 Out
3 min read
Python | Padding a string upto fixed length
Given a string, the task is to pad string up to given specific length with whitespaces. Let's discuss few methods to solve the given task.Method #1: Using ljust() C/C++ Code # Python code to demonstrate # pad spaces in string # upto fixed length # initialising string ini_string = "123abcjw
3 min read
Python - Value list lengths
Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the length of list as tuple attribute. Letâs discuss certain
5 min read
Python | Lead and Trail padding of strings list
Sometimes, while working with string lists, we can have a problem in which we need to pad each string in the list with a particular string. This type of problem can come in many places in the web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using lis
7 min read
Python - Find maximum length sub-list in a nested list
In Python, we often work with nested lists (lists inside lists), and sometimes we need to find out which sub-list has the most items. In this article, we will explore Various methods to Find the maximum length of a sub-list in a nested list. Using max() Function with key=lenThe simplest and most eff
2 min read
Python program to omit K length Rows
Given a Matrix, remove rows with length K. Input : test_list = [[4, 7], [8, 10, 12, 8], [10, 11], [6, 8, 10]], K = 2 Output : [[8, 10, 12, 8], [6, 8, 10]] Explanation : [4, 7] and [10, 11] omitted as length 2 rows. Input : test_list = [[4, 7], [8, 10, 12, 8], [10, 11], [6, 8, 10]], K = 3 Output : [[
3 min read
How To Find the Length of a List in Python
The length of a list refers to the number of elements in the list. There are several methods to determine the length of a list in Python. For example, consider a list l = [1, 2, 3, 4, 5], length of this list is 5 as it contains 5 elements in it. Let's explore different methods to find the length of
2 min read