0

For example, this simple code for outputting the middle character of a word - if it has a middle character.

string = str(input("String: "))

print(list(letter for letter in string if letter == string[((len(string) - 1) // 2)]))

Could I have the input inside of the list comp whilst still being able to reference the length of it in another part? Usually I do something like this with my inputs in list comp:

print(''.join(str(y) for y in [x for x in str(input("Please enter a string: ")) 
if x.isnumeric() == False]))

Just wanting to learn more about list comp's possibilities.

DyingInCS
  • 51
  • 5
  • 1
    btw, the `str` in `str(input(...))` is redundant. This is because `input()` always returns a `str`. Just use: `string = input(...)`. – quamrana Jan 22 '22 at 18:00
  • 1
    *Could I have the input inside of the list comp whilst still being able to reference the length of it in another part?* No, since Python does not support assignment expressions in list comprehensions. – Richard Neumann Jan 22 '22 at 18:02
  • 1
    @RichardNeumann reading this: https://stackoverflow.com/questions/10291997/how-can-i-do-assignments-in-a-list-comprehension it seems that it is possible. However, I think the resulting code won't be too readable. –  Jan 22 '22 at 18:04
  • @EyalGolan Clarification: Assignment expression cannot be used in a comprehension iterable expression. – Richard Neumann Jan 22 '22 at 18:09
  • @RichardNeumann But isn't this what is suggested here: https://stackoverflow.com/questions/31642577/multiline-user-input-with-list-comprehension-in-python-3 ? –  Jan 22 '22 at 18:11

2 Answers2

3

One approach is to store it inside its own list and unpack it using for

string = input("String: ")

would become

for string in [input("String: ")]

>>> print([letter for string in [input("String: ")] for letter in string if letter == string[(len(string) - 1) // 2]])
String: abcde
['c']

formatted over multiple lines:

>>> print(
...     [letter for string in [input("String: ")]
...             for letter in string
...             if letter == string[(len(string) - 1) // 2]]
... )

Also, your logic may have undesired behaviour.

String: abcdecccccc
['c', 'c', 'c', 'c', 'c', 'c', 'c']
  • Aha, completely missed that lmao. Converted another thing a function I had that did this into list comp and just didn't clock the loop ig. Thanks for the help :) – DyingInCS Jan 22 '22 at 19:53
1

If I wanted to cram something like this onto one line I'd use a lambda:

>>> print((lambda x: x[(len(x) - 1) // 2])(input()))
middle
d

In this case I think readability is vastly improved by doing the variable assignment on its own line, though.

Samwise
  • 68,105
  • 3
  • 30
  • 44