python - trouble with using list comprehensions & input() -


trying write list comprehension can iterate through string input() , create list each character of string having it's own index.

in essence, want function this:

x = ["00.00"[h] h in range(len("00.00"))] print(x) > ['0', '0', '.', '0', '0'] 

when putting actual string ("00.00") in there, python want do. refuses take input() same way:

>>> x = [input()[h] h in range(len(input()))] >  traceback (most recent call last):   file "<stdin>", line 1, in <module>   file "<stdin>", line 1, in <listcomp> indexerror: string index out of range 

the word "what" in there inputted, same else i've put in. i'm not sure what's different input() changes how indexes work. it?

you produced rather long-winded spelling of list(). there no need use list comprehension here:

list(input()) 

what goes wrong expression @ front of list comprehension evaluated for every single iteration; call input() first string, every character in string call input() again, time input not same string.

if ever need list comprehension on string, iterate on string directly. python for loop for each construct, there no need generate index; example, filter input produce list of lowercase ascii letters, there no need use range():

[char char in input() if 'a' <= char <= 'b'] 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -