I'm trying to split strings inside a list and store it in another list. My code is giving me a "List index out of range" error.
line_split = []
for i in range(len(phrase)):
line_split[i] = phrase[i].split()
gap = length % len(phrase[i])
phrase = ['Lorem ipsum dolor sit amet,', 'consectetur adipiscing elit,', 'sed do eiusmod tempor', 'incididunt ut labore et', 'dolore magna aliqua.']
That's because line_split
s an empty list, so even index 0 is out-of-range...
Use append
instead of indexing as so -
line_split.append(phrase[i].split())
Also, this can be done with a simple list-comprehension, which is readable and compact:
phrase = ['Lorem ipsum dolor sit amet,', 'consectetur adipiscing elit,', 'sed do eiusmod tempor', 'incididunt ut labore et', 'dolore magna aliqua.']
line_split = [p.split() for p in phrase]
Last but not least - I don't know what " gap
" is supposed to be, but length
is undefined...
Aswell as appending you can initialize the list with empty values:
line_split = [""] * len(phrase)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.