for w in r])]
r is a file with a list of words (separated by newlines) i'm reading and i'm choosing a random word there
however, when i try to generate more than one word:
words = [random.choice([w for w in r]) for _ in range(8)]
i get an error message IndexError: Cannot choose from an empty sequence, where empty sequence refers to the file i'm reading. how did adding that for loop there change a different list comprehension?
File objects in python act as iterators (hence why you can do "for line in file"), which are "consumed" once they're iterated over. When the list comprehension here does the first iteration, the file is read and consumed. You have to read the lines of the file and save it to a variable before doing the list comprehension.
_w = [w for w in r] words = [random.choice(_w) for _ in range(8)] worked for me
Btw, you can just do words = random.choices(_w, k=8). Notice it's the choice*s* function
oh cool, didn't know that, thanks!!
the random module's content is progressive discovery thing https://t.me/c/1111136772/179583
Обсуждают сегодня