I'm new to python, I'm trying to create a list of lists from a text file. The task seems easy to do but I don't know why it's not working with my code.
I have the following lines in my text file:
word1,word2,word3,word4
word2,word3,word1
word4,word5,word6
I want to get the following output:
[['word1','word2','word3','word4'],['word2','word3','word1'],['word4','word5','word6']]
The following is the code I tried:
mylist =[]
list =[]
with open("file.txt") as f:
for line in f:
mylist = line.strip().split(',')
list.append(mylist)
mylist =[]is useless, and you really shouldn't uselistas a variable name). Don't you get the desired output when youprint list?listas a variable name, but it's not a reserved word, otherwise it would be a syntax error to use it as a variable name (try usingfor,while, orfromas variable names).listis the name of a built-in class, and you are free to redefine it if you really want to, but generally that's not a good idea.