I want to replicate the functionality of the following code using a list comprehension:
with open('file.txt', 'w') as textfile:
for i in range(1, 6):
textfile.write(str(i) + '\n')
I tried the following:
with open('file.txt', 'w') as textfile:
textfile.write(str([i for i in range(1, 6)]) + '\n')
but it (understandably) prints [1, 2, 3, 4, 5], instead of one number on a single line.
I don't have an answer to 'Why would you want to do that?'; I just want to see if it's possible. Thanks!
EDIT: Thank you all for the replies; for some reason I was under the impression that list comprehensions are always encapsulated in [].
[]. generator expressions are surrounded by()and can also be passed directly to functions without doubling the(())