Skip to content

How to take the list as input in Python | Example code

  • by

Use an input() function with a split() function to take the list as input in Python. Using a split() function will split an input string by space.

Example take the list as input in Python

Simple example code input() function to accept the list elements from a user in the format of a string separated by space. And The split() method splits a string into a list.

input_string = input('Enter separated by space: ')

user_list = input_string.split()

# print list
print('list: ', user_list)


How to take the list as input in Python

Using command-line arguments: If you want to take a list as input from the command line when running the script, you can use the sys.argv list from the sys module. The first element of this list (sys.argv[0]) is the name of the script itself, and the subsequent elements are the command-line arguments provided when running the script. Here’s an example:

import sys

# Get the list of command-line arguments (excluding the script name)
input_list = sys.argv[1:]

# Convert the elements to their appropriate data type if needed
# For example, if you want a list of integers:
input_list = [int(element) for element in input_list]

print("Input list:", input_list)

Please note that the command-line argument approach requires you to run the script from the command line and provide the list elements as arguments after the script name. The input() function approach, on the other hand, allows users to input the list directly during runtime.

Comment if you have any doubts or suggestions on this Python List input code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *