Change language

# Python | Extract strings of size K

|

Method # 1: Using List Comprehension + len()
A combination of the above functions can be used to accomplish this task. In this case, we iterate over all rows and return only K-sized rows checked with len ().

 # Python3 code to demonstrate how it works # Extract K-sized lines # using a list comprehension + len ()   # initialize list test_list = [ ’gfg’ , ’is’ , ’ best’ , ’for’ , ’geeks’ ]    # print original list print ( "The original list:" + str (test_list))   # initialize K K = 3   # Extract K-sized lines # using list comprehension + len () res = [ele for ele in test_list if len (ele ) = = K]   # print 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’]

Method # 2: Using filter () + lambda
A combination of the above functions can be used to accomplish this task. In this we extract the elements using filter () and the logic is compiled into a lambda function.

 # Python3 code to demonstrate how it works # Extract K-sized lines # using filter () + lambd   # initialize the list test_list = [ ’gfg’ , ’is’ , ’ best’ , ’for’ , ’ geeks’ ]   # p Printing original list print ( "The original list: " + str (test_list))   # initialize K K = 3    # Extract K-sized lines # using () + lambda filter res = list ( filter ( lambda ele: len (ele) = = K, test_list))   # print 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’]

## Shop

Best laptop for Fortnite

\$

Best laptop for Excel

\$

Best laptop for Solidworks

\$

Best laptop for Roblox

\$

Best computer for crypto mining

\$

Best laptop for Sims 4

\$

Best laptop for Zoom

\$499

Best laptop for Minecraft

\$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

NUMPYNUMPY

How to convert Nonetype to int or string?

NUMPYNUMPY

How to specify multiple return types using type-hints

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

## Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method