Filter list by length of words





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I am trying to filter a list where there are words line by line, by the length of the word(between 4 and 8 characters). So that if the input file has:




  • hello

  • communication

  • be

  • dog

  • test


The output file is:




  • hello

  • test


So I have this code:



dir = "lower.lst"
dict = open(dir, 'r').readlines()
f=open('dictionary','w')
for word in dict:
if len(word)>=4 & len(word)<=8:
f.write(word)
f.close()
print(len(dict))

print(f)


But the output file keeps all the words.
By the way is there any more efficient way to do this?










share|improve this question


















  • 4





    & is a C-ism (or Java, or JavaScript). Python uses and.

    – usr2564301
    Nov 23 '18 at 19:00











  • Possible duplicate of Using the AND and NOT Operator in Python

    – usr2564301
    Nov 23 '18 at 19:02






  • 2





    Don't use dict as variable name.

    – Austin
    Nov 23 '18 at 19:03


















1















I am trying to filter a list where there are words line by line, by the length of the word(between 4 and 8 characters). So that if the input file has:




  • hello

  • communication

  • be

  • dog

  • test


The output file is:




  • hello

  • test


So I have this code:



dir = "lower.lst"
dict = open(dir, 'r').readlines()
f=open('dictionary','w')
for word in dict:
if len(word)>=4 & len(word)<=8:
f.write(word)
f.close()
print(len(dict))

print(f)


But the output file keeps all the words.
By the way is there any more efficient way to do this?










share|improve this question


















  • 4





    & is a C-ism (or Java, or JavaScript). Python uses and.

    – usr2564301
    Nov 23 '18 at 19:00











  • Possible duplicate of Using the AND and NOT Operator in Python

    – usr2564301
    Nov 23 '18 at 19:02






  • 2





    Don't use dict as variable name.

    – Austin
    Nov 23 '18 at 19:03














1












1








1








I am trying to filter a list where there are words line by line, by the length of the word(between 4 and 8 characters). So that if the input file has:




  • hello

  • communication

  • be

  • dog

  • test


The output file is:




  • hello

  • test


So I have this code:



dir = "lower.lst"
dict = open(dir, 'r').readlines()
f=open('dictionary','w')
for word in dict:
if len(word)>=4 & len(word)<=8:
f.write(word)
f.close()
print(len(dict))

print(f)


But the output file keeps all the words.
By the way is there any more efficient way to do this?










share|improve this question














I am trying to filter a list where there are words line by line, by the length of the word(between 4 and 8 characters). So that if the input file has:




  • hello

  • communication

  • be

  • dog

  • test


The output file is:




  • hello

  • test


So I have this code:



dir = "lower.lst"
dict = open(dir, 'r').readlines()
f=open('dictionary','w')
for word in dict:
if len(word)>=4 & len(word)<=8:
f.write(word)
f.close()
print(len(dict))

print(f)


But the output file keeps all the words.
By the way is there any more efficient way to do this?







python list filter






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 '18 at 18:57









Tecno DroneTecno Drone

61




61








  • 4





    & is a C-ism (or Java, or JavaScript). Python uses and.

    – usr2564301
    Nov 23 '18 at 19:00











  • Possible duplicate of Using the AND and NOT Operator in Python

    – usr2564301
    Nov 23 '18 at 19:02






  • 2





    Don't use dict as variable name.

    – Austin
    Nov 23 '18 at 19:03














  • 4





    & is a C-ism (or Java, or JavaScript). Python uses and.

    – usr2564301
    Nov 23 '18 at 19:00











  • Possible duplicate of Using the AND and NOT Operator in Python

    – usr2564301
    Nov 23 '18 at 19:02






  • 2





    Don't use dict as variable name.

    – Austin
    Nov 23 '18 at 19:03








4




4





& is a C-ism (or Java, or JavaScript). Python uses and.

– usr2564301
Nov 23 '18 at 19:00





& is a C-ism (or Java, or JavaScript). Python uses and.

– usr2564301
Nov 23 '18 at 19:00













Possible duplicate of Using the AND and NOT Operator in Python

– usr2564301
Nov 23 '18 at 19:02





Possible duplicate of Using the AND and NOT Operator in Python

– usr2564301
Nov 23 '18 at 19:02




2




2





Don't use dict as variable name.

– Austin
Nov 23 '18 at 19:03





Don't use dict as variable name.

– Austin
Nov 23 '18 at 19:03












5 Answers
5






active

oldest

votes


















2















  • Use the with-statement to automatically close files (even with exceptions are encountered).


  • & in Python is really for bit twiddling only, use and.

  • You don't actually need and, because comparisons can be chained. (len(word)>=4 and len(word)<=8 is equivalent to 4 <= len(word) <= 8).

  • In your question you use .readlines() and here I use for line in fin:. Either way the resulting strings will end in newline characters, so your length measurements will be off by one. I correct for this by stripping the line before taking the length (len(line.strip())). (Your code as written should have omitted 'be', but kept 'dog', because it's really 'dogn' which has a length of 4).

  • You said your code kept all of the words. To my eye your code should have worked to omit 'communicationn' and 'ben'. I could imagine that 'ben' might be kept if there were extra spaces after it in the file ('be n' has a length of 5 because of the two spaces). But there seems to be no logical way that 'communicationn' would be kept in your output file. You may want to double check that it really was there.




with open('lower.lst', 'r') as fin, open('dictionary', 'w') as fout:
for line in fin:
if 4 <= len(line.strip()) <= 8:
fout.write(line)





share|improve this answer


























  • Nifty way of opening the 2 files at once, but shouldn't you use readlines() before for line in fin:?

    – Pedro Lobito
    Nov 23 '18 at 19:20













  • @PedroLobito: Files iterate by line. readlines() buffers all the lines into a list first, but if all you're going to do is iterate over that list you should just cutout the middleman and iterate directly. This is especially important if the file is larger than working memory. (Both methods will give lines that include the newline at the end. That impacts this problem.)

    – Steven Rumbalski
    Nov 23 '18 at 19:24





















1














There are more than one choice to do this.




  1. With filter() built-in function


Check the docs here.



Let's suppose you have list of strings called data, then:



data = ['hello', 'communication', 'be', 'dog', 'test']
filtered_list = filter(lambda x: len(x) > 4 and len(x) < 8, data)
print(filtered_list)


Will return:



Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
>
['hello']


You can change the lambda function to filter different conditions. Filter will "catch" every element that returns True.




  1. With list-comprehension


This is probably the shortest way to achieve this. Just need to do:



filtered_list = [x for x in data if len(x) > 4 and len(x) < 8]





share|improve this answer


























  • When the OP wrote "between 4 and 8 characters" I believe he meant that as having inclusive endpoints so that word lengths of 4 and 8 would also be preserved. If so, your > and < should be >= and <=. Also a clearer way to write that is 4 <= len(x) <= 8 without the and. Finally, it would be worth mentioning in your answer that the OP has an additional bug because he's reading from file. His words have newlines at the end, so his length measurements are off by one.

    – Steven Rumbalski
    Nov 23 '18 at 19:43





















0














List comprehension does let you choose which elements you want to construct your list from. Here's an example implementation:



s = """
hello
communication
be
dog
test
"""

lst = [elm for elm in s.split() if (len(elm) >= 4 and len(elm) <= 8)]

print(lst)


Output:



['hello', 'test']





share|improve this answer































    0














    Is this what you're looking for? Here I use file context managers with the with reserved word, and I use and instead of & as noted in the comments.



    with open("lower.lst", "r") as f:
    o = [word for word in f if (len(word) >= 4 and len(word) <= 8)]

    with open("outfile.lst", "w") as f:
    f.write(o)


    It's a bit tough to know if this will format exactly to your intentions in the outfile.






    share|improve this answer































      0














      Your code should work if you replace & for and, i.e:





      dict = open("lower.lst", 'r').readlines()
      with open('dictionary','w') as f:
      for word in dict:
      if len(word)>=4 and len(word)<=8:
      f.write(word)





      share|improve this answer


























      • readlines() preserves the newlines, so the length test will need to account for that: if 4 <= len(word.strip()) <= 8:. This also impacts the write: f.write(word).

        – Steven Rumbalski
        Nov 23 '18 at 19:11













      • I used a list as example... thank you for pointing that.

        – Pedro Lobito
        Nov 23 '18 at 19:11














      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53451761%2ffilter-list-by-length-of-words%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2















      • Use the with-statement to automatically close files (even with exceptions are encountered).


      • & in Python is really for bit twiddling only, use and.

      • You don't actually need and, because comparisons can be chained. (len(word)>=4 and len(word)<=8 is equivalent to 4 <= len(word) <= 8).

      • In your question you use .readlines() and here I use for line in fin:. Either way the resulting strings will end in newline characters, so your length measurements will be off by one. I correct for this by stripping the line before taking the length (len(line.strip())). (Your code as written should have omitted 'be', but kept 'dog', because it's really 'dogn' which has a length of 4).

      • You said your code kept all of the words. To my eye your code should have worked to omit 'communicationn' and 'ben'. I could imagine that 'ben' might be kept if there were extra spaces after it in the file ('be n' has a length of 5 because of the two spaces). But there seems to be no logical way that 'communicationn' would be kept in your output file. You may want to double check that it really was there.




      with open('lower.lst', 'r') as fin, open('dictionary', 'w') as fout:
      for line in fin:
      if 4 <= len(line.strip()) <= 8:
      fout.write(line)





      share|improve this answer


























      • Nifty way of opening the 2 files at once, but shouldn't you use readlines() before for line in fin:?

        – Pedro Lobito
        Nov 23 '18 at 19:20













      • @PedroLobito: Files iterate by line. readlines() buffers all the lines into a list first, but if all you're going to do is iterate over that list you should just cutout the middleman and iterate directly. This is especially important if the file is larger than working memory. (Both methods will give lines that include the newline at the end. That impacts this problem.)

        – Steven Rumbalski
        Nov 23 '18 at 19:24


















      2















      • Use the with-statement to automatically close files (even with exceptions are encountered).


      • & in Python is really for bit twiddling only, use and.

      • You don't actually need and, because comparisons can be chained. (len(word)>=4 and len(word)<=8 is equivalent to 4 <= len(word) <= 8).

      • In your question you use .readlines() and here I use for line in fin:. Either way the resulting strings will end in newline characters, so your length measurements will be off by one. I correct for this by stripping the line before taking the length (len(line.strip())). (Your code as written should have omitted 'be', but kept 'dog', because it's really 'dogn' which has a length of 4).

      • You said your code kept all of the words. To my eye your code should have worked to omit 'communicationn' and 'ben'. I could imagine that 'ben' might be kept if there were extra spaces after it in the file ('be n' has a length of 5 because of the two spaces). But there seems to be no logical way that 'communicationn' would be kept in your output file. You may want to double check that it really was there.




      with open('lower.lst', 'r') as fin, open('dictionary', 'w') as fout:
      for line in fin:
      if 4 <= len(line.strip()) <= 8:
      fout.write(line)





      share|improve this answer


























      • Nifty way of opening the 2 files at once, but shouldn't you use readlines() before for line in fin:?

        – Pedro Lobito
        Nov 23 '18 at 19:20













      • @PedroLobito: Files iterate by line. readlines() buffers all the lines into a list first, but if all you're going to do is iterate over that list you should just cutout the middleman and iterate directly. This is especially important if the file is larger than working memory. (Both methods will give lines that include the newline at the end. That impacts this problem.)

        – Steven Rumbalski
        Nov 23 '18 at 19:24
















      2












      2








      2








      • Use the with-statement to automatically close files (even with exceptions are encountered).


      • & in Python is really for bit twiddling only, use and.

      • You don't actually need and, because comparisons can be chained. (len(word)>=4 and len(word)<=8 is equivalent to 4 <= len(word) <= 8).

      • In your question you use .readlines() and here I use for line in fin:. Either way the resulting strings will end in newline characters, so your length measurements will be off by one. I correct for this by stripping the line before taking the length (len(line.strip())). (Your code as written should have omitted 'be', but kept 'dog', because it's really 'dogn' which has a length of 4).

      • You said your code kept all of the words. To my eye your code should have worked to omit 'communicationn' and 'ben'. I could imagine that 'ben' might be kept if there were extra spaces after it in the file ('be n' has a length of 5 because of the two spaces). But there seems to be no logical way that 'communicationn' would be kept in your output file. You may want to double check that it really was there.




      with open('lower.lst', 'r') as fin, open('dictionary', 'w') as fout:
      for line in fin:
      if 4 <= len(line.strip()) <= 8:
      fout.write(line)





      share|improve this answer
















      • Use the with-statement to automatically close files (even with exceptions are encountered).


      • & in Python is really for bit twiddling only, use and.

      • You don't actually need and, because comparisons can be chained. (len(word)>=4 and len(word)<=8 is equivalent to 4 <= len(word) <= 8).

      • In your question you use .readlines() and here I use for line in fin:. Either way the resulting strings will end in newline characters, so your length measurements will be off by one. I correct for this by stripping the line before taking the length (len(line.strip())). (Your code as written should have omitted 'be', but kept 'dog', because it's really 'dogn' which has a length of 4).

      • You said your code kept all of the words. To my eye your code should have worked to omit 'communicationn' and 'ben'. I could imagine that 'ben' might be kept if there were extra spaces after it in the file ('be n' has a length of 5 because of the two spaces). But there seems to be no logical way that 'communicationn' would be kept in your output file. You may want to double check that it really was there.




      with open('lower.lst', 'r') as fin, open('dictionary', 'w') as fout:
      for line in fin:
      if 4 <= len(line.strip()) <= 8:
      fout.write(line)






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 23 '18 at 19:35

























      answered Nov 23 '18 at 19:13









      Steven RumbalskiSteven Rumbalski

      33.9k66095




      33.9k66095













      • Nifty way of opening the 2 files at once, but shouldn't you use readlines() before for line in fin:?

        – Pedro Lobito
        Nov 23 '18 at 19:20













      • @PedroLobito: Files iterate by line. readlines() buffers all the lines into a list first, but if all you're going to do is iterate over that list you should just cutout the middleman and iterate directly. This is especially important if the file is larger than working memory. (Both methods will give lines that include the newline at the end. That impacts this problem.)

        – Steven Rumbalski
        Nov 23 '18 at 19:24





















      • Nifty way of opening the 2 files at once, but shouldn't you use readlines() before for line in fin:?

        – Pedro Lobito
        Nov 23 '18 at 19:20













      • @PedroLobito: Files iterate by line. readlines() buffers all the lines into a list first, but if all you're going to do is iterate over that list you should just cutout the middleman and iterate directly. This is especially important if the file is larger than working memory. (Both methods will give lines that include the newline at the end. That impacts this problem.)

        – Steven Rumbalski
        Nov 23 '18 at 19:24



















      Nifty way of opening the 2 files at once, but shouldn't you use readlines() before for line in fin:?

      – Pedro Lobito
      Nov 23 '18 at 19:20







      Nifty way of opening the 2 files at once, but shouldn't you use readlines() before for line in fin:?

      – Pedro Lobito
      Nov 23 '18 at 19:20















      @PedroLobito: Files iterate by line. readlines() buffers all the lines into a list first, but if all you're going to do is iterate over that list you should just cutout the middleman and iterate directly. This is especially important if the file is larger than working memory. (Both methods will give lines that include the newline at the end. That impacts this problem.)

      – Steven Rumbalski
      Nov 23 '18 at 19:24







      @PedroLobito: Files iterate by line. readlines() buffers all the lines into a list first, but if all you're going to do is iterate over that list you should just cutout the middleman and iterate directly. This is especially important if the file is larger than working memory. (Both methods will give lines that include the newline at the end. That impacts this problem.)

      – Steven Rumbalski
      Nov 23 '18 at 19:24















      1














      There are more than one choice to do this.




      1. With filter() built-in function


      Check the docs here.



      Let's suppose you have list of strings called data, then:



      data = ['hello', 'communication', 'be', 'dog', 'test']
      filtered_list = filter(lambda x: len(x) > 4 and len(x) < 8, data)
      print(filtered_list)


      Will return:



      Python 3.6.1 (default, Dec 2015, 13:05:11)
      [GCC 4.8.2] on linux
      >
      ['hello']


      You can change the lambda function to filter different conditions. Filter will "catch" every element that returns True.




      1. With list-comprehension


      This is probably the shortest way to achieve this. Just need to do:



      filtered_list = [x for x in data if len(x) > 4 and len(x) < 8]





      share|improve this answer


























      • When the OP wrote "between 4 and 8 characters" I believe he meant that as having inclusive endpoints so that word lengths of 4 and 8 would also be preserved. If so, your > and < should be >= and <=. Also a clearer way to write that is 4 <= len(x) <= 8 without the and. Finally, it would be worth mentioning in your answer that the OP has an additional bug because he's reading from file. His words have newlines at the end, so his length measurements are off by one.

        – Steven Rumbalski
        Nov 23 '18 at 19:43


















      1














      There are more than one choice to do this.




      1. With filter() built-in function


      Check the docs here.



      Let's suppose you have list of strings called data, then:



      data = ['hello', 'communication', 'be', 'dog', 'test']
      filtered_list = filter(lambda x: len(x) > 4 and len(x) < 8, data)
      print(filtered_list)


      Will return:



      Python 3.6.1 (default, Dec 2015, 13:05:11)
      [GCC 4.8.2] on linux
      >
      ['hello']


      You can change the lambda function to filter different conditions. Filter will "catch" every element that returns True.




      1. With list-comprehension


      This is probably the shortest way to achieve this. Just need to do:



      filtered_list = [x for x in data if len(x) > 4 and len(x) < 8]





      share|improve this answer


























      • When the OP wrote "between 4 and 8 characters" I believe he meant that as having inclusive endpoints so that word lengths of 4 and 8 would also be preserved. If so, your > and < should be >= and <=. Also a clearer way to write that is 4 <= len(x) <= 8 without the and. Finally, it would be worth mentioning in your answer that the OP has an additional bug because he's reading from file. His words have newlines at the end, so his length measurements are off by one.

        – Steven Rumbalski
        Nov 23 '18 at 19:43
















      1












      1








      1







      There are more than one choice to do this.




      1. With filter() built-in function


      Check the docs here.



      Let's suppose you have list of strings called data, then:



      data = ['hello', 'communication', 'be', 'dog', 'test']
      filtered_list = filter(lambda x: len(x) > 4 and len(x) < 8, data)
      print(filtered_list)


      Will return:



      Python 3.6.1 (default, Dec 2015, 13:05:11)
      [GCC 4.8.2] on linux
      >
      ['hello']


      You can change the lambda function to filter different conditions. Filter will "catch" every element that returns True.




      1. With list-comprehension


      This is probably the shortest way to achieve this. Just need to do:



      filtered_list = [x for x in data if len(x) > 4 and len(x) < 8]





      share|improve this answer















      There are more than one choice to do this.




      1. With filter() built-in function


      Check the docs here.



      Let's suppose you have list of strings called data, then:



      data = ['hello', 'communication', 'be', 'dog', 'test']
      filtered_list = filter(lambda x: len(x) > 4 and len(x) < 8, data)
      print(filtered_list)


      Will return:



      Python 3.6.1 (default, Dec 2015, 13:05:11)
      [GCC 4.8.2] on linux
      >
      ['hello']


      You can change the lambda function to filter different conditions. Filter will "catch" every element that returns True.




      1. With list-comprehension


      This is probably the shortest way to achieve this. Just need to do:



      filtered_list = [x for x in data if len(x) > 4 and len(x) < 8]






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 23 '18 at 19:14

























      answered Nov 23 '18 at 19:02









      ChecheCheche

      823219




      823219













      • When the OP wrote "between 4 and 8 characters" I believe he meant that as having inclusive endpoints so that word lengths of 4 and 8 would also be preserved. If so, your > and < should be >= and <=. Also a clearer way to write that is 4 <= len(x) <= 8 without the and. Finally, it would be worth mentioning in your answer that the OP has an additional bug because he's reading from file. His words have newlines at the end, so his length measurements are off by one.

        – Steven Rumbalski
        Nov 23 '18 at 19:43





















      • When the OP wrote "between 4 and 8 characters" I believe he meant that as having inclusive endpoints so that word lengths of 4 and 8 would also be preserved. If so, your > and < should be >= and <=. Also a clearer way to write that is 4 <= len(x) <= 8 without the and. Finally, it would be worth mentioning in your answer that the OP has an additional bug because he's reading from file. His words have newlines at the end, so his length measurements are off by one.

        – Steven Rumbalski
        Nov 23 '18 at 19:43



















      When the OP wrote "between 4 and 8 characters" I believe he meant that as having inclusive endpoints so that word lengths of 4 and 8 would also be preserved. If so, your > and < should be >= and <=. Also a clearer way to write that is 4 <= len(x) <= 8 without the and. Finally, it would be worth mentioning in your answer that the OP has an additional bug because he's reading from file. His words have newlines at the end, so his length measurements are off by one.

      – Steven Rumbalski
      Nov 23 '18 at 19:43







      When the OP wrote "between 4 and 8 characters" I believe he meant that as having inclusive endpoints so that word lengths of 4 and 8 would also be preserved. If so, your > and < should be >= and <=. Also a clearer way to write that is 4 <= len(x) <= 8 without the and. Finally, it would be worth mentioning in your answer that the OP has an additional bug because he's reading from file. His words have newlines at the end, so his length measurements are off by one.

      – Steven Rumbalski
      Nov 23 '18 at 19:43













      0














      List comprehension does let you choose which elements you want to construct your list from. Here's an example implementation:



      s = """
      hello
      communication
      be
      dog
      test
      """

      lst = [elm for elm in s.split() if (len(elm) >= 4 and len(elm) <= 8)]

      print(lst)


      Output:



      ['hello', 'test']





      share|improve this answer




























        0














        List comprehension does let you choose which elements you want to construct your list from. Here's an example implementation:



        s = """
        hello
        communication
        be
        dog
        test
        """

        lst = [elm for elm in s.split() if (len(elm) >= 4 and len(elm) <= 8)]

        print(lst)


        Output:



        ['hello', 'test']





        share|improve this answer


























          0












          0








          0







          List comprehension does let you choose which elements you want to construct your list from. Here's an example implementation:



          s = """
          hello
          communication
          be
          dog
          test
          """

          lst = [elm for elm in s.split() if (len(elm) >= 4 and len(elm) <= 8)]

          print(lst)


          Output:



          ['hello', 'test']





          share|improve this answer













          List comprehension does let you choose which elements you want to construct your list from. Here's an example implementation:



          s = """
          hello
          communication
          be
          dog
          test
          """

          lst = [elm for elm in s.split() if (len(elm) >= 4 and len(elm) <= 8)]

          print(lst)


          Output:



          ['hello', 'test']






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 23 '18 at 19:03









          AyxanAyxan

          2,347722




          2,347722























              0














              Is this what you're looking for? Here I use file context managers with the with reserved word, and I use and instead of & as noted in the comments.



              with open("lower.lst", "r") as f:
              o = [word for word in f if (len(word) >= 4 and len(word) <= 8)]

              with open("outfile.lst", "w") as f:
              f.write(o)


              It's a bit tough to know if this will format exactly to your intentions in the outfile.






              share|improve this answer




























                0














                Is this what you're looking for? Here I use file context managers with the with reserved word, and I use and instead of & as noted in the comments.



                with open("lower.lst", "r") as f:
                o = [word for word in f if (len(word) >= 4 and len(word) <= 8)]

                with open("outfile.lst", "w") as f:
                f.write(o)


                It's a bit tough to know if this will format exactly to your intentions in the outfile.






                share|improve this answer


























                  0












                  0








                  0







                  Is this what you're looking for? Here I use file context managers with the with reserved word, and I use and instead of & as noted in the comments.



                  with open("lower.lst", "r") as f:
                  o = [word for word in f if (len(word) >= 4 and len(word) <= 8)]

                  with open("outfile.lst", "w") as f:
                  f.write(o)


                  It's a bit tough to know if this will format exactly to your intentions in the outfile.






                  share|improve this answer













                  Is this what you're looking for? Here I use file context managers with the with reserved word, and I use and instead of & as noted in the comments.



                  with open("lower.lst", "r") as f:
                  o = [word for word in f if (len(word) >= 4 and len(word) <= 8)]

                  with open("outfile.lst", "w") as f:
                  f.write(o)


                  It's a bit tough to know if this will format exactly to your intentions in the outfile.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 23 '18 at 19:03









                  Charles LandauCharles Landau

                  2,8031317




                  2,8031317























                      0














                      Your code should work if you replace & for and, i.e:





                      dict = open("lower.lst", 'r').readlines()
                      with open('dictionary','w') as f:
                      for word in dict:
                      if len(word)>=4 and len(word)<=8:
                      f.write(word)





                      share|improve this answer


























                      • readlines() preserves the newlines, so the length test will need to account for that: if 4 <= len(word.strip()) <= 8:. This also impacts the write: f.write(word).

                        – Steven Rumbalski
                        Nov 23 '18 at 19:11













                      • I used a list as example... thank you for pointing that.

                        – Pedro Lobito
                        Nov 23 '18 at 19:11


















                      0














                      Your code should work if you replace & for and, i.e:





                      dict = open("lower.lst", 'r').readlines()
                      with open('dictionary','w') as f:
                      for word in dict:
                      if len(word)>=4 and len(word)<=8:
                      f.write(word)





                      share|improve this answer


























                      • readlines() preserves the newlines, so the length test will need to account for that: if 4 <= len(word.strip()) <= 8:. This also impacts the write: f.write(word).

                        – Steven Rumbalski
                        Nov 23 '18 at 19:11













                      • I used a list as example... thank you for pointing that.

                        – Pedro Lobito
                        Nov 23 '18 at 19:11
















                      0












                      0








                      0







                      Your code should work if you replace & for and, i.e:





                      dict = open("lower.lst", 'r').readlines()
                      with open('dictionary','w') as f:
                      for word in dict:
                      if len(word)>=4 and len(word)<=8:
                      f.write(word)





                      share|improve this answer















                      Your code should work if you replace & for and, i.e:





                      dict = open("lower.lst", 'r').readlines()
                      with open('dictionary','w') as f:
                      for word in dict:
                      if len(word)>=4 and len(word)<=8:
                      f.write(word)






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 23 '18 at 19:12

























                      answered Nov 23 '18 at 19:07









                      Pedro LobitoPedro Lobito

                      50.9k16138172




                      50.9k16138172













                      • readlines() preserves the newlines, so the length test will need to account for that: if 4 <= len(word.strip()) <= 8:. This also impacts the write: f.write(word).

                        – Steven Rumbalski
                        Nov 23 '18 at 19:11













                      • I used a list as example... thank you for pointing that.

                        – Pedro Lobito
                        Nov 23 '18 at 19:11





















                      • readlines() preserves the newlines, so the length test will need to account for that: if 4 <= len(word.strip()) <= 8:. This also impacts the write: f.write(word).

                        – Steven Rumbalski
                        Nov 23 '18 at 19:11













                      • I used a list as example... thank you for pointing that.

                        – Pedro Lobito
                        Nov 23 '18 at 19:11



















                      readlines() preserves the newlines, so the length test will need to account for that: if 4 <= len(word.strip()) <= 8:. This also impacts the write: f.write(word).

                      – Steven Rumbalski
                      Nov 23 '18 at 19:11







                      readlines() preserves the newlines, so the length test will need to account for that: if 4 <= len(word.strip()) <= 8:. This also impacts the write: f.write(word).

                      – Steven Rumbalski
                      Nov 23 '18 at 19:11















                      I used a list as example... thank you for pointing that.

                      – Pedro Lobito
                      Nov 23 '18 at 19:11







                      I used a list as example... thank you for pointing that.

                      – Pedro Lobito
                      Nov 23 '18 at 19:11




















                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53451761%2ffilter-list-by-length-of-words%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                      Alcedinidae

                      Origin of the phrase “under your belt”?