Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do we assign values to variables in a list using a loop in Python?
In Python, lists are a useful way to store multiple elements in a single variable. To assign values to each entry in a list, loops are often needed. This strategy simplifies the process and improves the clarity of your code. This chapter will look at how to assign values to variables in a list using different loop types, using basic examples.
Using Simple Loop Iterations
In this method, we use the while loop to continuously prompt the user for input and append elements to the list. When we do not enter any element into the list and just press the Enter key, the loop breaks. To append the elements to the list, we use the append() method.
Example
The following is an example to assign values to variables in a list using a loop in Python using the append() method −
items_list = []
while True:
item = input("Enter new item or press enter if you want to exit: ")
if item == '':
break
items_list.append(item)
print("List:", items_list)
When you run the program, it will show this output −
Enter new item or press enter if you want to exit: 5 Enter new item or press enter if you want to exit: 9 Enter new item or press enter if you want to exit: 6 Enter new item or press enter if you want to exit: List: ['5', '9', '6']
Using the globals() Method
The globals() method retrieves the current global symbol table's dictionary. A symbol table is a data structure that a compiler maintains, which contains all of the program's necessary information. This method allows you to dynamically create variables from a list of names.
Example
The following is an example to assign values to variables in a list using a loop in Python using the globals() method −
var_names = ["one", "two", "three"]
count = 1
for name in var_names:
globals()[name] = count
count += 1
print(one)
print(two)
print(three)
After running the program, you will get this result −
1 2 3
Using List Comprehension
List comprehension provides a concise way to create lists. In this program, we will use list comprehension to create a list of even numbers by iterating through a range and applying a condition.
# Using list comprehension to generate even numbers from 0 to 10 # includes i if it is even even_numbers = [i for i in range(11) if i % 2 == 0] print(even_numbers)
This output will be displayed when the program runs −
[0, 2, 4, 6, 8, 10]
Using Nested Loops to Create a Multiplication Table
In this example, we will use nested loops to create a multiplication table. The outer loop iterates through the numbers 1 to 5, and the inner loop multiplies each number by the current number of the outer loop to create rows and columns.
# Creating an empty list for the multiplication table
multiplication_table = []
# Using nested loops to generate the table
for i in range(1, 6): # Iterate through rows
row = [] # Create an empty row
# Iterate over columns
for j in range(1, 6):
# Multiply and add to the current row
row.append(i * j)
# Append the created row to the table
multiplication_table.append(row)
print(multiplication_table)
You will see this result after executing the program −
[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]
Using For Loop with Range
You can also use a for loop with range() to assign values directly to list indices. This approach is useful when you know the size of the list in advance.
# Create a list with 5 empty elements
numbers = [0] * 5
# Assign values using a for loop
for i in range(len(numbers)):
numbers[i] = i * 2
print(numbers)
The output will be −
[0, 2, 4, 6, 8]
Conclusion
Python provides multiple ways to assign values to variables in a list using loops. Use simple loops for user input, list comprehension for concise creation, and nested loops for complex data structures like tables.
