-4

How do I remove sublist from 2d list with list comprehension if string length is greater than 7? I only know how to do it in regular single dimension list.

Effort:

simple_list=['apple', 'banana', 'cantaloupe', 'durian']
mylist=[['apple'], ['banana'], ['cantaloupe'], ['durian']]
short_list = [blist for blist in simple_list if len (blist) <= 7]

Want:

short_list=[['apple'], ['banana'], ['durian']]
  • 1
    You cannot remove with list comprehension - but you can make _another_ list with the unwanted strings removed. Also, do not use `list` as a variable name. – DYZ Feb 22 '22 at 17:23
  • 1
    What if you have `['cantaloupe', 'pear']`? Why do you need list of lists? – OneCricketeer Feb 22 '22 at 17:24
  • 2
    @OneCricketeer how about "The question should be updated to include desired behavior, _a specific problem or error_, and the _shortest code necessary_ to reproduce the problem." – Pranav Hosangadi Feb 22 '22 at 17:29
  • @OneCrickteer It is to me. Zero-effort questions take time away from the genuine ones that do need help. You’re entitled to your opinion and not required to vote. – Abhijit Sarkar Feb 22 '22 at 17:30
  • @AbhijitSarkar Updated the question now. I only know how to do it with regular list. I don't want to reduce 2d list into 1d list. – anonymously132526 Feb 22 '22 at 18:34
  • https://stackoverflow.com/q/6340351/839733 – Abhijit Sarkar Feb 22 '22 at 18:37
  • @AbhijitSarkar yea sure I can reduce 2d list into 1d list and or use a loop. But the question here is how to do it with list comprehension without having to reduce the list from 2d into 1d. I think the question is specific on point and fully valid and should remain open. – anonymously132526 Feb 22 '22 at 18:42
  • With your edit, what is the purpose of `mylist`? – OneCricketeer Feb 22 '22 at 21:23
  • @OneCricketeer knew only how to comprehend simple_list. mylist is what I have and wanted to comprehend but did'nt know how. mylist will be used to add more data like weight, etc. and I liked it structured the way it is as 2d list. – anonymously132526 Feb 24 '22 at 10:12

1 Answers1

0

For each value in the list, return it, if all the elements of the sublist have length less-than-or-equal-to 6

[x for x in mylist if all(len(y) <= 6 for y in x)]

You can also create a list from the singular string elements, but unclear why you'd want this

>>> simple_list=['apple', 'banana', 'cantaloupe', 'durian']
>>> short_list = [[blist] for blist in simple_list if len (blist) <= 7]
>>> short_list
[['apple'], ['banana'], ['durian']]
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245