How do we assign values to variables in a list using a loop in Python?


In this article we will discuss different ways to assign values to variables in a list using loops in python.

Using simple loop iterations

In this method we use the for loop for appending elements into the lists. When we do not enter any element into the list and stop appending, then we just press the enter key.

To append the elements into the list we use the append() method.

Example 1

The following is an example to assign values to the variables in a list using a loop in python using append() method.

L=[] while True: item=input("enter new item or press enter if you want to exit ") if item=='': break L.append(item) print ("List : ",L)

Output

On executing the above code, the following output is obtained.

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']

Example 2

In the following example, the variable name is being introduced in the exec statement −

var_names = ['one','two','three'] count = 1 for n in var_names: exec ("%s = %s" % (n, count)) count +=1 print ('The values assigned to the variables are:',one, two, three)

Output

Following is an output of the above code −

 The values assigned to the variables are: 1 2 3

Using the globals() method

In the following example, we use the globals() built-in method. You can access the dictionary of global variables with 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.

Example 3

The following is an example to assign values to the variables in a list using a loop in python using 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)

Output

On executing the above code, the following output is obtained.

 1
 2
 3

Updated on: 04-Apr-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements