Last modified: Feb 15, 2023 By Alexander Williams
How to Update Variable [string, list, dictionary] in for Loop Python
Variable is a storage of information and [string, list, tuple, dictionary] are types of information that we store in a variable. However, in this tutorial, we'll see how to update a variable in for loop.
If you are ready let's get started.
Update String in for Loop
In the following example, we'll update a string in for loop:
# String
my_string = "String"
# For loop
for i in ["List", "Tuple", "Dictionary"]:
my_string = i
# Print my_string
print(my_string)
## Output: Dictionary
First, we assigned "String" to the my_string variable. Then we've loop over ["List", "Tuple", "Dictionary"]. Finally, we've updated my_string.
As you can see, Before the loop my_string="Srtring" and after the loop my_string="Dictionary".
Let's do another example with the range() function.
# String
my_string = "String"
# For loop
for i in range(10):
if i > 5:
# Update my_string
my_string = i
break
# Print my_string
print(my_string)
## Output: 6
Here we've updated my_str to an integer.
Update List in for Loop
Also, we can update a list in for loop. However, in the following example, we'll see how to update it:
# List
my_list = [1, 2, 3]
# For loop
for i in ["List", "Tuple", "Dict"]:
# Check if item is "List"
if i == "List":
my_list[0] = i
# Print my_list
print(my_list)
## Output: ['List', 2, 3]
Let me explain:
- We've declared the my_list variable with a list in the value
- We've looped over a list
- We've updated my_list after checking the item value if it is "Dict"
Update Dictionary in for Loop
We can also update Dictionary in for loop. However, we'll the same thing as the list example.
# Dictionary
my_dic = {"name":"Leo", "age":15}
# For loop
for i in ["List", "Tuple", "Dict"]:
# Check if item is "Dict"
if i == "Dict":
my_dic['age'] = i
# Print my_dic
print(my_dic)
## Output: {'name': 'Leo', 'age': 'Dict'}
That's it!
Conclusion
Allright! I think we've covered all about how to update a variable in the loop over. You can visit How to Properly Check if a Variable is Not Null in Python To learn how to check null or none variable.
Happy learning ♥