Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Remove all strings from a list of tuples
Next article icon

Python – Fill Strings for size K in Tuple List

Last Updated : 18 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes while working with Tuple lists, we can have a problem in which we need to perform filling of strings to complete certain size in lists. This type of ask can occur in data domains and data preprocessing. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [(‘Gfg’, ‘is’), (‘best’, ‘for’), (‘CS’, ‘Geeks’)], K = 6, fill_char = ‘#’ 
Output : [(‘Gfg###’, ‘is####’), (‘best##’, ‘for###’), (‘CS####’, ‘Geeks#’)] 

Input : test_list = [(‘Gfg’, ‘is’), (‘best’, ‘for’), (‘CS’, ‘Geeks’)], K = 5, fill_char = ‘!’ 
Output : [(‘Gfg!!’, ‘is!!!’), (‘best!’, ‘for!!’), (‘CS!!!’, ‘Geeks’)]

Method #1 : Using list comprehension + len() This functionality is shorthand to brute force method that can be applied to solve this problem. In this, we perform task of checking for K size using len(), and perform required fill by a character. 

Python3




# Python3 code to demonstrate working of
# Fill Strings for size K in Tuple List
# Using list comprehension + len()
 
# initializing list
test_list = [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 8
 
# initializing fill_char
fill_char = '*'
 
# Fill Strings for size K in Tuple List
# Using list comprehension + len()
res = [(a + fill_char * (K - len(a)), b + fill_char * (K - len(b))) for a, b in test_list]
 
# printing result
print("The modified list : " + str(res))
 
 
Output : 
The original list is : [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')] The modified list : [('Gfg*****', 'is******'), ('best****', 'for*****'), ('CS******', 'Geeks***')]

Time Complexity: O(n*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 #2 : Using list comprehension + ljust() The combination of above functions can be used to solve this problem. In this, we perform the task of filling trailing characters using ljust(). 

Python3




# Python3 code to demonstrate working of
# Fill Strings for size K in Tuple List
# Using list comprehension + ljust()
 
# initializing list
test_list = [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 8
 
# initializing fill_char
fill_char = '*'
 
# Fill Strings for size K in Tuple List
# Using list comprehension + ljust()
res = [(a.ljust(K, fill_char), b.ljust(K, fill_char)) for a, b in test_list]
 
# printing result
print("The modified list : " + str(res))
 
 
Output : 
The original list is : [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')] The modified list : [('Gfg*****', 'is******'), ('best****', 'for*****'), ('CS******', 'Geeks***')]

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 Lambda Function and Map

Approach

The approach here is to use the map() function to apply a lambda function to each string in each tuple in the input list. The lambda function concatenates the fill character with the string until the resulting string has a length of K. The resulting map objects are then converted back to tuples and returned as a list of tuples.

Algorithm

1. Define a lambda function fill_func that takes a string and returns the string concatenated with the fill character up to the size of K.
2. Use a list comprehension to iterate through each tuple in the input list test_list.
3. Use the map() function to apply the fill_func lambda function to each string in the current tuple tpl, and convert the resulting map object to a tuple.
4. Append the resulting tuple to a list result.
5. Return the list of tuples with the filled strings.

Python3




def fill_strings_map(test_list, K, fill_char):
    # Define a lambda function that takes a string and returns the string concatenated with the fill character up to the size of K
    fill_func = lambda string: string + fill_char * (K - len(string))
    # Use the map() function to apply the lambda function to each string in each tuple in the list, and convert the resulting map objects to tuples
    result = [tuple(map(fill_func, tpl)) for tpl in test_list]
    # Return the list of tuples with the filled strings
    return result
test_list = [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
K=5
fill_char='!'
print(fill_strings_map(test_list, K, fill_char))
 
 
Output
[('Gfg!!', 'is!!!'), ('best!', 'for!!'), ('CS!!!', 'Geeks')]

 Time complexity: O(nmk), where n is the number of tuples in the input list, m is the number of strings in each tuple, and k is the length of the longest string in the input list. However, in practice, the function is likely to have a much lower time complexity, as most input lists will be small and have relatively short strings.

Auxiliary Space: O(nmk), where n, m, and k are as defined above. Additionally, the function creates a new lambda function, which has a space complexity of O(1). However, in practice, the lambda function is likely to have a negligible space complexity compared to the size of the input list.

Method #4 :Using nested loops and string concatenation:

Algorithm:

1.Iterate over each tuple in the given list.
2.For each tuple, get the two strings.
3.Check the length of each string.
4.If the length is less than K, append fill_char to the string until the length becomes equal to K.
5.Append the modified tuple to the result list.
6.Return the result list.

Python3




# Python3 code to demonstrate working of
# Fill Strings for size K in Tuple List
# Using for loop
 
# initializing list
test_list = [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 8
 
# initializing fill_char
fill_char = '*'
 
# Fill Strings for size K in Tuple List
# Using for loop
res = []
for tpl in test_list:
    s1 = tpl[0]
    s2 = tpl[1]
    if len(s1) < K:
        s1 += fill_char * (K - len(s1))
    if len(s2) < K:
        s2 += fill_char * (K - len(s2))
    res.append((s1, s2))
 
# printing result
print("The modified list : " + str(res))
# This code is contributed by Jyothi pinjala.
 
 
Output
The original list is : [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')] The modified list : [('Gfg*****', 'is******'), ('best****', 'for*****'), ('CS******', 'Geeks***')]

Time Complexity: O(N*K), where N is the number of tuples in the input list and K is the length of the strings to be filled.

Auxiliary Space: O(N*K), the space required to store the modified tuples in the result list.

Method#5: Using Recursive method.

In the recursive case, the method takes the first tuple in the list and extracts the two strings a and b. It then constructs a new tuple with a and b filled up to size K using the fill_char character. This new tuple is then concatenated with the result of recursively calling the method with the rest of the list.

Note that this method is less efficient than the list comprehension method because it uses recursion and creates new tuples for each element. However, it demonstrates an alternative approach to solving the problem using recursion.

Python3




def fill_strings_recursive(test_list, K, fill_char):
    if not test_list:
        return []
    a, b = test_list[0]
    return [(a + fill_char * (K - len(a)), b + fill_char * (K - len(b)))] + fill_strings_recursive(test_list[1:], K, fill_char)
# initializing list
test_list = [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 8
 
# initializing fill_char
fill_char = '*'
res = fill_strings_recursive(test_list,K,fill_char)
 
# printing result
print("The modified list : " + str(res))
 
 
Output
The original list is : [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')] The modified list : [('Gfg*****', 'is******'), ('best****', 'for*****'), ('CS******', 'Geeks***')]

Time complexity:

Best case: O(1) when the input list is empty.
Worst case: O(n*K) where n is the length of the input list and K is the size to fill strings up to. This is because the method needs to iterate over each tuple in the list, and for each tuple it needs to construct a new tuple with filled strings up to size K. The operation of filling a string takes O(K) time.
Auxiliary Space:

Best case: O(1) when the input list is empty.
Worst case: O(n*K) where n is the length of the input list and K is the size to fill strings up to. This is because the method needs to create a new tuple for each tuple in the input list with filled strings up to size K. The space needed to store a tuple with filled strings is proportional to K.

Method#6: Using re module

Algorithm:

  1. Initialize the original list of tuples.
  2. Set the value of K to the desired length of the strings.
  3. Set the fill character to the character that will be used to fill the strings.
  4. Using list comprehension, iterate over the list of tuples.
  5. For each tuple, apply the zip_longest() function from the itertools module to the two strings, left-justifying them with the fill character to a length of K.
  6. Concatenate the two formatted strings using the format() method with the appropriate format string.
  7. Return the modified list of tuples.

Python3




import re
 
test_list = [('Gfg', 'is'), ('best', 'for'), ('CS', 'Geeks')]
K = 8
fill_char = '*'
 
filler = fill_char * (K - 1)  # create a string of K-1 fill_char characters
 
res = [tuple(re.sub(fr'\b(\w{{1,{K}}})\b', fr'\1{filler}', s) for s in tpl) for tpl in test_list]
print(res)
 
 
Output
[('Gfg*******', 'is*******'), ('best*******', 'for*******'), ('CS*******', 'Geeks*******')]

Time Complexity:
The time complexity of this approach is O(n), where n is the number of tuples in the list. The zip_longest() function has a time complexity of O(max(len(a), len(b))), where a and b are the strings being zipped. Since the strings are padded to a fixed length of K, the zip_longest() function will have a time complexity of O(K) for each tuple. Therefore, the overall time complexity of the algorithm is O(n*K).

Auxiliary Space Complexity:
The auxiliary space complexity of this approach is O(n*K), where n is the number of tuples in the list and K is the length of the padded strings. This is because the modified list of tuples is stored in memory, and each string in the tuples has a maximum length of K.



Next Article
Python | Remove all strings from a list of tuples
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Remove all strings from a list of tuples
    Given a list of tuples, containing both integer and strings, the task is to remove all strings from list of tuples. Examples: Input : [(1, 'Paras'), (2, 'Jain'), (3, 'GFG'), (4, 'Cyware')] Output : [(1), (2), (3), (4)] Input : [('string', 'Geeks'), (2, 225), (3, '111')] Output : [(), (2, 225), (3,)]
    8 min read
  • Python | Flatten Tuples List to String
    Sometimes, while working with data, we can have a problem in which we need to perform interconversion of data. In this, we can have a problem of converting tuples list to a single String. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + join() The
    7 min read
  • How To Slice A List Of Tuples In Python?
    In Python, slicing a list of tuples allows you to extract specific subsets of data efficiently. Tuples, being immutable, offer a stable structure. Use slicing notation to select ranges or steps within the list of tuples. This technique is particularly handy when dealing with datasets or organizing i
    3 min read
  • Python - Filter String Tuples if String lengths equals K
    Given List of tuples, filter tuples, whose element strings have length equal to K. Input : test_list = [("ABC", "Gfg", "CS1"), ("Gfg", "Best"), ("Gfg", "WoOW")], K = 3 Output : [('ABC', 'Gfg', 'CS1')] Explanation : All Strings have length 3 in above tuple. Input : test_list = [("ABCD", "Gfg", "CS1")
    6 min read
  • Python | Convert String to tuple list
    Sometimes, while working with Python strings, we can have a problem in which we receive a tuple, list in the comma-separated string format, and have to convert to the tuple list. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + split() + replace() This is a br
    5 min read
  • Convert List Of Tuples To Json String in Python
    We have a list of tuples and our task is to convert the list of tuples into a JSON string in Python. In this article, we will see how we can convert a list of tuples to a JSON string in Python. Convert List Of Tuples To Json String in PythonBelow, are the methods of Convert List Of Tuples To Json St
    3 min read
  • Convert list of strings to list of tuples in Python
    Sometimes we deal with different types of data types and we require to inter-convert from one data type to another hence interconversion is always a useful tool to have knowledge. This article deals with the converse case. Let's discuss certain ways in which this can be done in Python. Method 1: Con
    5 min read
  • Convert List to Tuple in Python
    The task of converting a list to a tuple in Python involves transforming a mutable data structure list into an immutable one tuple. Using tuple()The most straightforward and efficient method to convert a list into a tuple is by using the built-in tuple(). This method directly takes any iterable like
    2 min read
  • Find the Size of a Tuple in Python
    There are several ways to find the "size" of a tuple, depending on whether we are interested in the number of elements or the memory size it occupies. For Example: if we have a tuple like tup = (10, 20, 30, 40, 50), calling len(tup) will return 5, since there are five elements in the tuple. Using le
    3 min read
  • Convert List of Tuples to List of Strings - Python
    The task is to convert a list of tuples where each tuple contains individual characters, into a list of strings by concatenating the characters in each tuple. This involves taking each tuple, joining its elements into a single string, and creating a new list containing these strings. For example, gi
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences