Create a series of tuples using a for loop

I searched and cannot find the answer to this question, although I am sure that it already exists. I am very new to python, but I did such things before in other languages, I read a data file as a string, and I want to save each data string in my own tuple in order to access outside the for loop.

tup(i) = inLine 

where inLine is the line from the file, and tup(i) is the tuple in which it is stored. i increases as the cycle progresses. Then I can print any line using something similar to

 print tup(100) 
+4
source share
2 answers

Creating a tuple, as you describe in a loop, is not a great choice, as they are immutable.

This means that every time you add a new row to your tuple, you really create a new tuple with the same values ​​as the old one, plus your new row. This is ineffective and should generally be avoided.

If you only need to refer to strings by index, you can use a list:

 lines = [] for line in inFile: lines.append(line) print lines[3] 

If you really need a tuple, you can drop it after you are done:

 lines = tuple(lines) 
+3
source

The Python file file supports the file.readlines ([sizehint]) method, which reads the contents of the entire file and saves it as a list.

Alternatively, you can pass a file iterator object through a tuple to create a tuple of strings and index it the way you want

 #This will create a tuple of file lines with open("yourfile") as fin: tup = tuple(fin) #This is a straight forward way to create a list of file lines with open("yourfile") as fin: tup = fin.readlines() 
+1
source

All Articles