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:
Size of String in Memory - Python
Next article icon

Python | Extract K sized strings

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

Sometimes, while working with huge amount of data, we can have a problem in which we need to extract just specific sized strings. This kind of problem can occur during validation cases across many domains. Let's discuss certain ways to handle this in Python strings list.

Method #1 : Using list comprehension + len() 
The combination of above functionalities can be used to perform this task. In this, we iterate for all the strings and return only K sized strings checked using len().

Python3
# Python3 code to demonstrate working of # Extract K sized strings # using list comprehension + len()  # initialize list  test_list = ['gfg', 'is', 'best', 'for', 'geeks']  # printing original list  print("The original list : " + str(test_list))  # initialize K  K = 3  # Extract K sized strings # using list comprehension + len() res = [ele for ele in test_list if len(ele) == K]  # printing result print("The K sized strings are : " + str(res)) 

Output : 
The original list : ['gfg', 'is', 'best', 'for', 'geeks'] The K sized strings are : ['gfg', 'for']

 

Time Complexity: O(n), where n is the length of the input list. This is because we’re using list comprehension + len() 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 filter() + lambda 
The combination of above functionalities can be used to perform this task. In this, we extract the elements using filter() and logic is compiled in a lambda function.

Python3
# Python3 code to demonstrate working of # Extract K sized strings # using filter() + lambda  # initialize list  test_list = ['gfg', 'is', 'best', 'for', 'geeks']  # printing original list  print("The original list : " + str(test_list))  # initialize K  K = 3  # Extract K sized strings # using filter() + lambda res = list(filter(lambda ele: len(ele) == K, test_list))  # printing result print("The K sized strings are : " + str(res)) 

Output : 
The original list : ['gfg', 'is', 'best', 'for', 'geeks'] The K sized strings are : ['gfg', 'for']

 

Time complexity: O(n), where n is the length of the numbers list. The filter() + lambda function has a constant time complexity of O(n)

Auxiliary Space: O(n), as we create new list res where n is the length of the numbers list.

Method #3: Using map() function and lambda expression

Algorithm:

  1. Initialize the list and K
  2. Apply filter() and lambda expression to filter out the strings with length equal to K
  3. Apply map() and lambda expression to get the filtered strings
  4. Convert the result to a list
  5. Print the output

Below is the implementation of the above approach:

Python3
# initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks']  # printing original list print("The original list : " + str(test_list))  # initialize K K = 3  # Extract K sized strings # using map() function and lambda expression res = list(map(lambda x:x, filter(lambda x: len(x)==K, test_list)))  # printing result print("The K sized strings are : " + str(res)) 

Output
The original list : ['gfg', 'is', 'best', 'for', 'geeks'] The K sized strings are : ['gfg', 'for']

Time complexity:
The time complexity of filter() function is O(N) where N is the length of the list. The lambda function inside filter() function has a time complexity of O(1). The map() function also has a time complexity of O(N). The lambda function inside map() function has a time complexity of O(1). Therefore, the overall time complexity of the code is O(N).

Auxiliary space:
The space complexity of filter() function and map() function is O(1) as they are not creating any additional space. Therefore, the overall space complexity of the code is also O(N).

Method #4: Using a for loop

  • Initialize an empty list res to store the K sized strings.
  • Loop through each element ele in the input list test_list.
  • Check if the length of ele is equal to K. If yes, append ele to res.
  • Once all elements have been checked, return res.

Below is the implementation of the above approach:

Python3
# Python3 code to demonstrate working of # Extract K sized strings # using a for loop  # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks']  # printing original list print("The original list : " + str(test_list))  # initialize K K = 3  # Extract K sized strings # using a for loop res = [] for ele in test_list:     if len(ele) == K:         res.append(ele)  # printing result print("The K sized strings are : " + str(res)) 

Output
The original list : ['gfg', 'is', 'best', 'for', 'geeks'] The K sized strings are : ['gfg', 'for']

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(k), where k is the number of strings of length K in the input list (worst case is when all strings have length K and thus the new list will have k elements).


Next Article
Size of String in Memory - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Extract range sized strings
    Sometimes, while working with huge amount of data, we can have a problem in which we need to extract just specific range sized strings. This kind of problem can occur during validation cases across many domains. Let’s discuss certain ways to handle this in Python strings list. Method #1 : Using list
    4 min read
  • Python - Extract K length substrings
    The task is to extract all possible substrings of a specific length, k. This problem involves identifying and retrieving those substrings in an efficient way. Let's explore various methods to extract substrings of length k from a given string in Python Using List Comprehension List comprehension is
    3 min read
  • Python | K Character Split String
    The problems and at the same time applications of list splitting is quite common while working with python strings. Some characters are usually tend to ignore in the use cases. But sometimes, we might not need to omit those characters but include them in our programming output. Let’s discuss certain
    4 min read
  • Python Extract Substring Using Regex
    Python provides a powerful and flexible module called re for working with regular expressions. Regular expressions (regex) are a sequence of characters that define a search pattern, and they can be incredibly useful for extracting substrings from strings. In this article, we'll explore four simple a
    2 min read
  • Size of String in Memory - Python
    There can be situations in which we require to get the size that the string takes in bytes using Python which is usually useful in case one is working with files. Let's discuss certain ways in which this can be performed. Using sys.getsizeof()This task can also be performed by one of the system call
    2 min read
  • Python - Extract String till Numeric
    Given a string, extract all its content till first appearance of numeric character. Input : test_str = "geeksforgeeks7 is best" Output : geeksforgeeks Explanation : All characters before 7 are extracted. Input : test_str = "2geeksforgeeks7 is best" Output : "" Explanation : No character extracted as
    5 min read
  • Python - Frequency of K in sliced String
    Given a String, find the frequency of certain characters in the index range. Input : test_str = 'geeksforgeeks is best for geeks', i = 3, j = 9, K = 'e' Output : 0 Explanation : No occurrence of 'e' between 4th [s] and 9th element Input : test_str = 'geeksforgeeks is best for geeks', i = 0, j = 9, K
    6 min read
  • Python | Extract words from given string
    In Python, we sometimes come through situations where we require to get all the words present in the string, this can be a tedious task done using the native method. Hence having shorthand to perform this task is always useful. Additionally, this article also includes the cases in which punctuation
    4 min read
  • Python - Extract string between two substrings
    The problem is to extract the portion of a string that lies between two specified substrings. For example, in the string "Hello [World]!", if the substrings are "[" and "]", the goal is to extract "World". If the starting or ending substring is missing, handle the case appropriately (e.g., return an
    3 min read
  • Extract words starting with K in String List - Python
    In this article, we will explore various methods to extract words starting with K in String List. The simplest way to do is by using a loop. Using a LoopWe use a loop (for loop) to iterate through each word in the list and check if it starts with the exact character (case-sensitive) provided in the
    2 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