How do I treat the multiple lines in the body
By simplifying the expression down; you don't need multiple statements to build the nested list:
[i + 1, list(word)[i]]
gives you the same result as declaring x = []
and appending two the results of two expressions.
That would make the list comprehension
[
[i + 1, list(word)[i]]
for i in range(len(list(word)))
]
Next, you don't need to call list(word)
to get the length of a string or to address individual characters. Strings are already sequences, so len(word)
and word[i]
also work:
[
[i + 1, word[i]]
for i in range(len(word))
]
Next, if you used the enumerate()
function, you can generate both a running index to replace the range()
loop, and get access to the individual characters of word
without having to index; you can start the running index at 1
with a second argument to enumerate()
(the default is to start at 0
):
[[i, char] for i, char in enumerate(word, 1)]
If you don't have to have a list for each pair, just use enumerate(word, 1)
directly in loops and get tuples:
list(enumerate(word, 1))
Demo:
>>> word = "in_str"
>>> list(enumerate(word, 1))
[(1, 'i'), (2, 'n'), (3, '_'), (4, 's'), (5, 't'), (6, 'r')]
>>> [[i, char] for i, char in enumerate(word, 1)]
[[1, 'i'], [2, 'n'], [3, '_'], [4, 's'], [5, 't'], [6, 'r']]