Javatpoint Logo
Javatpoint Logo

Input a list in Python

In this article, we will discuss how we can input a list in Python. But before discussion their methods, we must know about the list in Python.

What is a List?

A list is a built-in data structure provided by Python, which enables the organization and storage of a collection of items. A list of mutable things is presented in a logical order and is enclosed in square brackets. Each list item is distinguished from the others by commas.

Example:

The list "drivers", which includes the elements "LEWIS", "GEORGE", "MAX", and "SEBASTIAN", is utilized in this illustration. A list can have entries made from strings, numbers, and even additional lists.

In Python, the List data structure is mutable, allowing the user to add, remove or update its elements. Lists support random access to their elements. The index of a list starts with 0, and all the required elements can be accessed through indexing.

Taking input

There are many ways to take input in Python. Some of them are mentioned below

1. Input():

Using Python's input() function, you can send user input to a list and save it as a string. After that, the input can be processed to generate a list format.

Example:

Output:

Enter elements of the list separated by space: 1 2 3 4 5
List: [1, 2, 3, 4, 5]

In this situation, the user is provoked to enter a list of things that are isolated by spaces. Utilizing the input() function, a string is separated into its part parts utilizing the split() technique. The things of results are changed over completely to numbers utilizing the list comprehension.

For instance, if the user types "1 2 3 4 5", the program will convert their input into the list [1, 2, 3, 4, 5] and print it as a result.

Depending on the types of components you anticipate in the list (such as strings, floats, and so on), you can modify the conversion technique or incorporate error handling to deal with improper inputs.

2. Using split() and map():

The input can be separated that sent to you as a string. After that, the items can be changed into the desired data type by giving each one a conversion function.

Example:

Output:

Enter elements of the list separated by space: 1 2 3 4 5
List: [1, 2, 3, 4, 5]

Split() is a built-in string method in Python. It breaks up a string into a list of substrings using a delimiter already passed as an argument. The inbuilt split() function works in such a way that it separates the input text into a number of segments mainly dependent on whitespace (such as tabs, spaces, or newline character) if a specific delimiter is not mentioned when used in the code.

The input text in the sample is divided into its component pieces using input_str.split(). The split() method halves the input string at each space, resulting in a list of substrings. For instance, split() will divide ["1", "2", "3", "4", "5"] if the user enters "1 2 3 4 5".

The results of applying a specified function to each item in an iterable (like a list) to an iterator are returned by Python's built-in map() method. In the example, the int() function is applied to each component of the divided input string using the map(int, input_str.split()) method.

The int() method converts a string that represents an integer into a real integer. We map int() to each element of the split input string to obtain a new iterable with the matching integer values. The statement map(int, ["1", "2", "3", "4", "5"]) will result in an iterator with the integers [1, 2, 3, 4, 5].

3. Using a Loop:

You can use a loop to repeatedly prompt the user for input and append each entered value to the list

Example:

Output:

Enter the number of elements: 4
Enter element 1: TESLA
Enter element 2: FORD
Enter element 3: FERRARI
Enter element 4: MERCEDES
List: ['TESLA','FORD','FERRARI', 'MERCEDES']

In this example, the user is prompted to enter the number of elements they want to input. Let's say they enter 4. Then, the program enters a loop that iterates 4 times using range(n). During each iteration, the user is prompted to enter an element, starting from Enter Element 1: and incrementing for subsequent iterations.

The user enters "TESLA", "FORD", "FERRARI", and "MERCEDES" as the appropriate elements in the preceding example. Every component is annexed to the my_list list utilizing the attach() technique.

  • Input validation: It's crucial to take input validation into account when processing a list of input. To ensure that the user provides accurate input, you might want to implement error handling. For instance, you could determine whether the input is within the desired format or range and ask the user to re-enter if an invalid input is found.
  • Splitting with custom delimiter: When splitting a string, the split() method by default uses whitespace characters as the delimiter. The split() method does allow you to give a custom delimiter as an argument, though. For instance, use input_str.split(',') to divide a comma-separated input.
  • Handling different data types: You might need to manage several data types in the input list depending on your needs. To change the input components' data types, use appropriate conversion operations like int(), float(), or str().
  • Prompting for list length: You can initially ask the user for the number of elements if you want input on the list's length. After that, you can assign the required resources and iterate the required number of times as a result.
  • Input formatting: In the prompt message, take into account letting the user know the intended input format. By doing so, you may prevent misunderstandings and ensures that the user enters the input in the correct manner.
  • Error handling: To avoid further misunderstandings, it is preferred to properly mention the input data format in the user prompt message so that we make ensure that the user enters the input in the required format.
  • Accepting Multi-line input: A loop can be used to get the input element for each iteration if the user wishes to provide input with multiple lines. It is useful if the input data has line breaks.

Output:

Enter elements of the listmy_list (press 'x' to finish):
LAMBORGHINI
FERRARI
MERCEDES AMG
X
The list will be :['LAMBORGHINI', 'FERRARI', 'MERCEDES AMG'].

Conclusion

Finally, we can conclude that the data to be taken as input, user preference and requirements, and the method to take user input can vary among the techniques discussed above.

If the user wants to take an input of a string, they can use the use of split() and map() to divide the given string into various segments depending on the delimiter provided correspondingly. The user can also do explicit type conversions to convert the data type of each created segment. This approach is useful when the input is separated by spaces or commas.

Furthermore, if the total number of input components is unknown ahead of time, a Dynamic Input process can be used to remind the user after each iteration to provide the next input element, which is added to the appropriate data structure.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA