Home > Mobile >  How to not print "empty" list in for loop - Python
How to not print "empty" list in for loop - Python

Time:03-29

The following list is a snippit of output of my code, as you can see it prints [] 3 times at the end, I want to figure out, how to get rid of them.

I have tried a combination of "if not [], 0, '', "", element" at the end of the list comprehension, but it doesn't seem to affect.

Code that outputs it:

list = [element.lower() for element in newline.split()]

OUTPUT:

['do', 'ordain', 'and', 'establish', 'this', 'constitution', 'for', 'the', 'united', 'states', 'of']
['america.']
[]
[]
[]

Edit:

    input_name = "file.txt"
    inputFile = open(input_name,"r")

    for element in input_name:
        #Reads input
        line = inputFile.readline()
        #Removes newline using slice
        newline = line[:-1] 
        #converts 
        list = [element.lower() for element in newline.split() if not '']
        print(list)

file.txt:

do ordain and establish this Constitution for the United States of America.

File is a paragraph of text

CodePudding user response:

This problem is occurring because you are, for some unknown reason, looping like this:

for element in input_name:
    ..

As input_name is a string, then this is looping over the characters in the string, meaning you attempt to read eight lines (one for each character in the string file.txt)

The length of input_name has nothing to do with the length of the file …

CodePudding user response:

I think what you want is to get rid of empty lists, so just judge the list itself. If you do something at the end of the list comprehension, you only affect the elements in the list.
If the list is empty like [], it will be False

temp_list = [element.lower() for element in newline.split()]
if temp_list:
    print(temp_list)
  • Related