Python | Construct N Range Equilength String list
Last Updated :
17 May, 2023
Sometimes, while working with Python, we can have a problem in which we need to construct a string list which contains N range numbers. But we have requirement in which we need to keep each element of equal length. Let's discuss certain ways in which this task can be performed.
Method #1: Using list comprehension + zfill() The combination of above functionalities can be used to perform this task. In this, we perform the task of adding numbers using list comprehension and zfill() takes care of length required for each string.
Python3
# Python3 code to demonstrate working of
# Construct N Range Equilength String list
# using list comprehension + zfill()
# initialize N
N = 6
# printing N
print("Number of elements required : " + str(N))
# initialize K
K = 3
# Construct N Range Equilength String list
# using list comprehension + zfill()
res = [str(ele).zfill(K) for ele in range(N)]
# printing result
print("K Length range strings list : " + str(res))
Output : Number of elements required : 6
K Length range strings list : ['000', '001', '002', '003', '004', '005']
Time Complexity: O(n), where n is the length of the input list. This is because we’re using list comprehension + zfill() which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #2 : Using map() + string formatting This task can also be performed using above functions. In this, we extend the logic of length using string formatting. And is used for constructing the N range.
Python3
# Python3 code to demonstrate working of
# Construct N Range Equilength String list
# using map() + string formatting
# initialize N
N = 6
# printing N
print("Number of elements required : " + str(N))
# initialize K
K = 3
# Construct N Range Equilength String list
# using map() + string formatting
temp = '{:0' + str(K) + '}'
res = list(map(temp.format, range(N)))
# printing result
print("K Length range strings list : " + str(res))
Output : Number of elements required : 6
K Length range strings list : ['000', '001', '002', '003', '004', '005']
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #3: Using List Comprehension + format method
Python3
# Python3 code to demonstrate working of
# Construct N Range Equilength String list
# using format method
# initialize N
N = 6
# printing N
print("Number of elements required : " + str(N))
# initialize K
K = 3
res = ['{:0{}}'.format(i, K) for i in range(N)]
# printing result
print("K Length range strings list : " + str(res))
#this code is contributed by edula vinay kumar reddy
OutputNumber of elements required : 6
K Length range strings list : ['000', '001', '002', '003', '004', '005']
Time complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using numpy:
Algorithm:
- Initialize N and K with integer values.
- Create a numpy array by using np.arange(N) which generates the range of numbers from 0 to N-1.
- Convert the numpy array elements to strings by using astype(str).
- Pad the left side of each string element with zeroes until the length of the string becomes K by using np.char.zfill() function.
- Convert the resulting numpy array back to a list by using tolist() method.
- Print the final list.
Python3
import numpy as np
# initialize N
N = 6
# printing N
print("Number of elements required : " + str(N))
# initialize K
K = 3
# create a numpy array of integers from 0 to N-1
arr = np.arange(N)
# convert the array of integers to an array of strings
# using astype() function of numpy
arr_str = arr.astype(str)
# use np.char.zfill() function to add leading zeros
# to each element of the array to make them K-length
res = np.char.zfill(arr_str, K)
# convert the numpy array back to a regular Python list
res_list = res.tolist()
# print the final list
print("K Length range strings list : " + str(res_list))
#This code is contributed by Jyothi pinjala
Output:
Number of elements required : 6
K Length range strings list : ['000', '001', '002', '003', '004', '005']
Time Complexity:
The time complexity of the algorithm is O(N) because we need to perform the following operations:
np.arange(N) - generates the range of numbers from 0 to N-1 which takes O(N) time.
astype(str) - converts the numpy array elements to strings which takes O(N) time.
np.char.zfill() - pads the left side of each string element with zeroes until the length of the string becomes K which takes O(N) time.
tolist() - converts the resulting numpy array back to a list which takes O(N) time.
Therefore, the overall time complexity of the algorithm is O(N).
Auxiliary Space:
The space complexity of the algorithm is also O(N) because we are creating a numpy array to hold the range of numbers from 0 to N-1, and then converting it to a list after padding each element with zeroes. Therefore, the overall space complexity of the algorithm is O(N).
Similar Reads
Python | Convert String ranges to list
Sometimes, while working in applications we can have a problem in which we are given a naive string that provides ranges separated by a hyphen and other numbers separated by commas. This problem can occur across many places. Let's discuss certain ways in which this problem can be solved. Method #1:
6 min read
Python - Concatenate Ranged Values in String list
Given list of strings, perform concatenation of ranged values from the Strings list. Input : test_list = ["abGFGcs", "cdforef", "asalloi"], i, j = 3, 5 Output : FGorll Explanation : All string sliced, FG, or and ll from all three strings and concatenated. Input : test_list = ["aGFGcs", "cforef", "aa
5 min read
First N letters String Construction - Python
The task of constructing a string from the first N letters of a given string in Python involves extracting a specific portion of the string, starting from the beginning and including the first N characters. For example, if we have the string "GeeksForGeeks" and want to extract the first 5 characters
3 min read
Python | Convert List of String List to String List
Sometimes while working in Python, we can have problems of the interconversion of data. This article talks about the conversion of list of List Strings to joined string list. Let's discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression + join() + isd
6 min read
Python - Ranged Maximum Element in String List
Sometimes, while working with Python data, we can have a problem in which we have data in form of String List and we require to find the maximum element in that data, but that also in a certain range of indices. This is quite peculiar problem but can have application in data domains. Let's discuss c
4 min read
Python | Alternate range slicing in list
List slicing is quite common utility in Python, one can easily slice certain elements from a list, but sometimes, we need to perform that task in non-contiguous manner and slice alternate ranges. Let's discuss how this particular problem can be solved. Method #1 : Using list comprehension List compr
6 min read
Convert List to Delimiter Separated String - Python
The task of converting a list to a delimiter-separated string in Python involves iterating through the list and joining its elements using a specified delimiter. For example, given a list a = [7, "Gfg", 8, "is", "best", 9] and a delimiter "*", the goal is to produce a single string where each elemen
3 min read
Python - Reverse Range in String List
Given a string list, reverse each element of string list from ith to jth index. Input : test_list = ["Geeksforgeeks", "Best", "Geeks"], i, j = 1, 2 Output : ['ee', 'es', 'ee'] Explanation : Range of strings are extracted. Input : test_list = ["Geeksforgeeks"], i, j = 1, 7 Output : ['eeksfor'] Explan
3 min read
Python | Concatenate N consecutive elements in String list
Sometimes, while working with data, we can have a problem in which we need to perform the concatenation of N consecutive Strings in a list of Strings. This can have many applications across domains. Let's discuss certain ways in which this task can be performed. Method #1: Using format() + zip() + i
8 min read
Python | Extract Score list of String
Sometimes, while programming we can have a problem in which we dedicate to each character of alphabets a particular score and then according to string, extract only those score for further computations. This can have application in gaming domain. Let's discuss certain ways in which this task can be
3 min read