WholesomeGhost
WholesomeGhost

Reputation: 1121

Adding input directly to a list

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 ?

Upvotes: 1

Views: 351

Answers (4)

boot-scootin
boot-scootin

Reputation: 12515

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().

Upvotes: 1

dl.meteo
dl.meteo

Reputation: 1766

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', '!']

Upvotes: 0

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160367

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: ')]

Upvotes: 2

Kevin
Kevin

Reputation: 76194

>>> 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']

Upvotes: 3

Related Questions