Damian Thomas Damian Thomas - 3 years ago 79
Python Question

trouble with using list comprehensions & input()

Trying to write a list comprehension that can iterate through a string from input() and create a list with each character of the string having it's own index.

In essence, I want a function that does this:

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


When putting an actual string ("00.00") in there, python does exactly what I want it to do. But it refuses to take an input() the same way:

>>> x = [input()[h] for h in range(len(input()))]
> what

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 is what i inputted, but it does the same for basically everything else I've put in. I'm not sure what's so different about input() that changes how the indexes work. What is it?

Answer Source

You produced a rather long-winded spelling of list(). There is no need to use list comprehension here:

list(input())

What goes wrong for you is that the expression at the front of the list comprehension is evaluated for every single iteration; so you call input() first to get a string, then for every character in that string you call input() again, but this time the input is not necessarily the same string.

If you ever do need a list comprehension over a string, just iterate over the string directly. The Python for loop is a for each construct, there is no need to generate an index; for example, to filter the input to produce a list of lowercase ASCII letters, there is no need to use range():

[char for char in input() if 'a' <= char <= 'b']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download