Nested List Input in Python: A Beginner’s Guide
Nested lists are a powerful data structure in Python. In this article, we will explore how to take input for a nested list in Python. Let’s consider the following example: [[‘B’, 21], [‘C’, 26], [‘A’, 34]]
To input elements for a nested list, we can use loops. Firstly, we need to create two lists — one for the final list and another for the sub-list. Then, we can use nested for loops to take input for the elements of the sub-list and append it to the final list.
In the outer loop, we need to iterate through the number of sub-lists in the list. In the inner loop, we can take input for the elements of the sub-list. After every iteration of the outer loop, we need to set the temporary list to null to avoid any previous values.
Here’s the code:
# Initialize an empty list to store the final output
my_list = []
# Initialize an empty temporary list to store each sub-list
temp_list = []
# Take input from the user for the number of sub-lists
n = int(input('Enter the number of sub-lists: '))
# Loop over the range of n to take input for each sub-list
for i in range(n):
# Loop over the range of 2 to take input for each element in the sub-list
for j in range(2):
# Take input from the user for the current element
temp_list.append(input())
# Append the current sub-list to the final list
my_list.append(temp_list)
# Reset the temporary list to an empty list for the next iteration
temp_list = []
# Print the final output
print(my_list)
Explanation:
- First, we initialize an empty list
my_list
to store the final output, and an empty temporary listtemp_list
to store each sub-list. - Then, we take input from the user for the number of sub-lists using
input()
and convert it to an integer usingint()
, and store it in the variablen
. - Next, we loop over the range of
n
usingfor i in range(n):
to take input for each sub-list. - Within this loop, we loop over the range of 2 using
for j in range(2):
to take input for each element in the sub-list. - We take input from the user for the current element using
input()
and append it to the temporary list usingtemp_list.append(input())
. - After we have taken input for all elements in the sub-list, we append the current sub-list to the final list using
my_list.append(temp_list)
. - We then reset the temporary list to an empty list for the next iteration using
temp_list = []
. - Finally, we print the final output using
print(my_list)
.
OUTPUT:
Enter the size of the list: 3
a
21
b
34
c
76
Input List: [['a', '21'], ['b', '34'], ['c', '76']]
I hope you found this article on how to take a nested list input in Python helpful. If you have any comments or suggestions, please feel free to leave them below. Don’t forget to like and share this article if you found it useful!
Also, if you would like to read more articles on Python, data engineering, or other technical topics, please follow me for more updates. Thank you for reading!