1

I am trying to shorten my code by putting input directly into a list. This is my code:

n = input('Enter: ')
lista = [n[i] for i in range(len(n))]

I am trying to put this in one line. I tried couple of variations but none of them worked. Is this even possible to do in python ?

2
  • It's possible, but I would not recommend it since you usually want to check for input correctness before using it. Commented Mar 21, 2017 at 14:33
  • 1
    Please don't tag a question with input in the code as python 2.7 AND 3.x Commented Mar 21, 2017 at 14:35

4 Answers 4

3
>>> lista = list(input("Enter: "))
Enter: hello
>>> lista
['h', 'e', 'l', 'l', 'o']

Or, if you insist that you absolutely must use a list comprehension for some reason,

>>> lista = (lambda n: [n[i] for i in range(len(n))])(input("Enter: "))
Enter: hello
>>> lista
['h', 'e', 'l', 'l', 'o']

Or, if all you actually wanted was to put the input into a list as a single element:

>>> lista = [input("Enter: ")]
Enter: hello
>>> lista
['hello']
Sign up to request clarification or add additional context in comments.

Comments

2

You don't even need to use a comprehension with range(len(n)) here since you're just creating a list out of each element in the string returned from input.

A one-line equivalent is simply using:

lista = list(input('Enter: ')) 

or, alternatively, for Python >= 3.5:

lista = [*input('Enter: ')]

Comments

1

What about:

letters = [letter for letter in input('Enter: ')]

Try it out:

>>> letters = [letter for letter in input('Enter: ')]
Enter: hello
>>> letters
['h', 'e', 'l', 'l', 'o']

Or if you enter a sentence and want individual words, use input('Enter: ').split().

Comments

0

Another useful way to parsing arguments from the command line to the python script is the package argparse.

The following example shows you how to parse arguments in a list:

import argparse

parser = argparse.ArgumentParser(description='Parse Arguments')
parser.add_argument('--to-list', nargs='+', help='read Arguments as a list')
args = parser.parse_args()

list = args.to-list

The usage would be:

python parseArguments.py --to-list Hello World !

>>> list
['Hello','World', '!']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.