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`]