In Python, we frequently need to create, modify, or manipulate lists based on a variety of situations or conditions. Python provides the types.List method which allows us to dynamically create lists at runtime. In this tutorial, we will show you how to create a list at runtime in Python.
Step 1: Understanding the Basics
A list in Python is a collection of items which can be of different types. The items in the list are separated with a comma (,) and enclosed in square brackets [].
Here is the simplest way to create a list in Python:
1 2 |
my_list = [] # an empty list my_list2 = [1, 2, 3, 4, 5] # a list of integers |
Step 2: Creating a List at Runtime
We can create a list at runtime by taking user input. Here is an example of creating a list by taking 5 integer inputs from the user:
1 2 3 4 |
my_list = [] # create an empty list for i in range(5): my_list.append(int(input('Enter the integer: '))) |
In the above code, we create an empty list and then use a for loop to call the Python input function which takes our input as a string, we then convert this input into an integer and append it to our list.
Step 3: Accessing the List Elements
The list elements can be accessed using their index number. The indexing starts from 0 in Python. Here is an example:
1 2 3 4 |
my_list = [1, 2, 3, 4, 5] # Access the first element print(my_list[0]) # Output: 1 |
The Full Code
1 2 3 4 5 6 7 |
my_list = [] # create an empty list for i in range(5): my_list.append(int(input('Enter the integer: '))) # Access the first element print(my_list[0]) |
Enter the integer: 13 Enter the integer: 34 Enter the integer: 45 Enter the integer: 24 Enter the integer: 63 13
Conclusion
This tutorial provided a guide on how to create a list at runtime in Python. Remember that list elements can be of any type, not just integers. The methods used in this tutorial such as input, append, and print are some of the most commonly used functions when dealing with lists in Python.
Be sure to practice using these functions to get comfortable with list manipulation in Python.