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!

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
    listofWordsinLines.extend(words)

print(listofWordsinLines)

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

print(setofWordsinLines)

"""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.

commented: Thank you, that was really helpful! +4

That looks great, Thanks.


Thanks for the variable name tip as well!

That looks great, Thanks.


Thanks for the variable name tip as well!

Close the thread solved?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.