954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

A bit stuck~ for statement, list and set!

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 myfor 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!

Qwazil
Junior Poster
106 posts since Nov 2006
Reputation Points: 19
Solved Threads: 0
Infraction Points: 5
 

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.

Lardmeister
Posting Virtuoso
1,749 posts since Mar 2007
Reputation Points: 407
Solved Threads: 44
 

That looks great, Thanks.


Thanks for the variable name tip as well!

Qwazil
Junior Poster
106 posts since Nov 2006
Reputation Points: 19
Solved Threads: 0
Infraction Points: 5
 

That looks great, Thanks.


Thanks for the variable name tip as well!

Qwazil
Junior Poster
106 posts since Nov 2006
Reputation Points: 19
Solved Threads: 0
Infraction Points: 5
 

Close the thread solved?

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You