def generator():
nums = ['09', '98', '87', '76', '65', '54', '43']
s_chars = ['*', '&', '^', '%', '$', '#', '@',]
data = open("list.txt", "w")
for c in s_chars:
for n in nums:
data.write(c + n)
data.close()
I would like to add a newline after every "c + n".
Change
to
A properly-placed
data.write('\n')
will handle that. Just indent it appropriately for the loop you want to punctuate.In the previously reply, I have made a wrong answer because I have misunderstood the requirements, please ignore it.
I think you can use
join
to simplify the inner loopThis one works for me
Pushing more work to the C layer with
writelines
andproduct
:This produces the same effect as the nested loop, but does so with builtins implemented in C (in the CPython reference interpreter anyway), removing byte code execution overhead from the picture; this can dramatically improve performance, particularly for larger inputs, and unlike other solutions involving
'\n'.join
of the whole output into a single string to perform a singlewrite
call, it's iterating as it writes, so peak memory usage remains fixed instead of requiring you to realize the entire output in memory all at once in a single string.OR
depending on what you want.