I have something like this:
for i in range(0,100,5):
text = ("Price\t",
foo[i+0].bar, "\t",
foo[i+1].bar, "\t",
foo[i+2].bar, "\t",
foo[i+3].bar, "\t",
foo[i+4].bar, "\t",
"Value", "\n")
file.writelines(text)
My problem is: let's assume that i=0
. For that case, it is certain that I will have foo[0]. But for indices 1,2,3,4 foo can be empty. For example, if foo is empty for indices greater than 2, I want my text to be like:
text = ("Price\t",
foo[0].bar, "\t",
foo[1].bar, "\t",
foo[2].bar, "\n")
I thought of using exceptions, but I guess, I will not be able to construct text
if I do not have all the indexed elements. (Iteration will stop?) So, what is the best practice to do that? I could not think of a short way to do it. Basically what I need is:
text= ("Price\t",
ifexist(foo[0].bar, "\t"),
ifexist(foo[1].bar, "\t"),
ifexist(foo[2].bar, "\t"),
ifexist(foo[3].bar, "\t"),
ifexist(foo[4].bar, "\t"),
"Value", "\n")
ps: Please do not forget I assumed i=0
for the sake of simplicity. But in fact, generally I am going to have more than hundred values.
edit: By saying "can be empty", I meant to say that the index might be beyond the size of the list.
edit2: Abot foo:
# start class
class Test:
def __init__(self, bar, bar2, bar3):
self.bar= a
self.bar2= b
self.bar3= c
# end class
for i in particular_list:
# read and parse the input file with indeces obtained from particular_list
# do calculations for temp_bar,temp_bar2,temp_bar3
foo.append(Test(temp_bar, temp_bar2, temp_bar3))