Home > Mobile >  Removing strings from a list dependent on their length?
Removing strings from a list dependent on their length?

Time:01-13

I am trying to remove any strings from this list of strings if their length is greater than 5. I don't know why it is only removing what seems to be random strings. Please help. The item for sublist part of the code just changes the list of lists, into a normal list of strings.

list2 = [['name'],['number'],['continue'],['stop'],['signify'],['tester'],['racer'],['stopping']]
li = [item for sublist in list2 for item in sublist]
var=0
for words in li:
if len(li[var])>5:
    li.pop()
var =1
print(li)

The output is: ['name', 'number', 'continue', 'stop', 'signify']

CodePudding user response:

Just include the check when flattening the list:

list2 = [['name'],['number'],['continue'],['stop'],['signify'],['tester'],['racer'],['stopping']]
li = [item for sublist in list2 for item in sublist if len(item) <= 5]
['name', 'stop', 'racer']

CodePudding user response:

You can use a list comprehension to build a new list with only items that are 5 or less in length.

>>> l = ['123456', '123', '12345', '1', '1234567', '12', '1234567']
>>> l = [x for x in l if len(x) <= 5]
>>> l
['123', '12345', '1', '12']
  •  Tags:  
  • Related