Hey all,

I'm a beginner.

When i feed a list of lines into this for statement, i have trouble getting the output into a set for use outside of the for statement.

ListofWordsinLines = {}
words = []
for line in ListOfLines:
    words = line.split()
    ListofWordsinLines = set(words)

if i print (ListofWordsinLines) in the loop i get the desired set.

As soon as i try to use it outside of the loop i only get the last line in the set. So if it was a block of text 10 lines long i only get the bottom line.

I know this is happening because my for line in WordFileRead: is addressing each line sequentially but my experience/knowledge doesn't let me figure out what to do next.

Thanks in advance!

8 Years
Discussion Span
Last Post by pyTony

Read the comments in this example code, it should show you how to solve your problem.

# data string for testing
data = """\
line one
line two
line three"""

# data list for testing
listOfLines = data.split('\n')

listofWordsinLines = []
for line in listOfLines:
    # words is a list
    words = line.split()
    # extend this list


# change list to a set
setofWordsinLines = set(listofWordsinLines)


"""my console display -->
['line', 'one', 'line', 'two', 'line', 'three']
{'line', 'three', 'two', 'one'}

Also, variable names starting with an upper case letter are customarily used for class names.

Edited by Lardmeister: n/a

Votes + Comments
Thank you, that was really helpful!

That looks great, Thanks.

Thanks for the variable name tip as well!


That looks great, Thanks.

Thanks for the variable name tip as well!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.