Python's for loop is an iterator-based loop [that's why bruno desthuilliers says that it "works for all iterables [lists, tuples, sets, dicts, iterators, generators etc]". A string is also another common type of iterable].
Let's say you have a list of tuples. Using that nomenclature you shared, one can iterate through both the keys and values simultaneously. For instance:
tuple_list = [[1, "Countries, Cities and Villages"],[2,"Animals"],[3, "Objects"]]
for k, v in tuple_list:
print[k, v]
will give you the output:
1 Countries, Cities and Villages
2 Animals
3 Objects
If you use a dictionary, you'll also gonna be able to do this. The difference here is the need for .items[]
dictionary = {1: "Countries, Cities and Villages", 2: "Animals", 3: "Objects"}
for k, v in dictionary.items[]:
print[k, v]
The difference between dictionary and dictionary.items[] is the following
dictionary: {1: 'Countries, Cities and Villages', 2: 'Animals', 3: 'Objects'}
dictionary.items[]: dict_items[[[1, 'Countries, Cities and Villages'], [2, 'Animals'], [3, 'Objects']]]
Using dictionary.items[] we'll get a view object containig the key-value pairs of the dictionary, as tuples in a list. In other words, with dictionary.items[] you'll also get a list of tuples. If you don't use it, you'll get
TypeError: cannot unpack non-iterable int object
If you want to get the same output using a simple list, you'll have to use something like enumerate[]
list = ["Countries, Cities and Villages","Animals", "Objects"]
for k, v in enumerate[list, 1]: # 1 means that I want to start from 1 instead of 0
print[k, v]
If you don't, you'll get
ValueError: too many values to unpack [expected 2]
So, this naturally raises the question... do I need always a list of tuples? No. Using enumerate[] we'll get an enumerate object.
Created: July-02, 2021 | Updated: October-02, 2021 A for
Loop for Multiple Assignments in a Dictionary in Pythonenumerate[]
Function for Multiple
Assignments in a List in Pythonzip[]
Function for Multiple Assignments in a Tuple or a List in Pythonfor
loop is used for iterating over any sequence, from a list to a tuple to a dictionary. It can even iterate over a string. This article discusses how to use the for
loop for multiple variables in Python.
The use of multiple variables in a for
loop in Python can be applied to lists or dictionaries, but it does not work for a general error. These multiple assignments of variables simultaneously, in the same line of code, are known as iterable unpacking.
Use the for
Loop for Multiple Assignments in a Dictionary in Python
A dictionary can be utilized to store the data values in key-value pairs. In simple terms, A dictionary maps one value to another, similar to how an English dictionary is used to map one word to its definition.
Here, we will use the items[]
method on the given Python dictionary. This function provides the output as a list that contains all the dictionary keys with their values.
The following code uses the for
loop for multiple assignments
in a dictionary.
dict1 = {1: "Bitcoin", 2: "Ethereum"}
for key, value in dict1.items[]:
print[f"Key {key} has value {value}"]
Output:
Key 1 has value Bitcoin
Key 2 has value Ethereum
In the code above, we also use the f-strings
method along with the print
function to implement the for
loop and display the key-value pairs.
Use the enumerate[]
Function for Multiple Assignments in a List in Python
The enumerate[]
function makes any collection into an enumerated object and returns
it. This method can be used when, say, we have two lists, and we’re going to work on both at the same time with the help of indexes to look for corresponding elements in the other list.
The following code uses the enumerate[]
function for multiple assignments in a list.
coins = ["Bitcoin", "Ethereum", "Cardano"]
prices = [48000,2585,2]
for i, coin in enumerate[coins]:
price = prices[i]
print[f"${price} for 1 {coin}"]
Output:
$48000 for 1 Bitcoin
$2585 for 1 Ethereum
$2 for 1 Cardano
Here, we take two lists, namely coins
and prices
, and simultaneously do the assignment on both of the lists. The enumerate
object provides the indexes, which is great and makes looping
over the two lists simultaneously an achievable task.
Use the zip[]
Function for Multiple Assignments in a Tuple or a List in Python
The zip[]
function is a built-in function offered in Python and is utilized to create an iterator that will interact with and combine elements from two or more given iterables.
The zip[]
function can be used for parallel interaction and can also make
unpacking several variables at a time possible. The following code uses the zip[]
function for multiple assignments in a tuple or a list.
coins = ["Bitcoin", "Ethereum", "Cardano"]
prices = [48000,2585,2]
for coin, price in zip[coins, prices]:
print[f"${price} for 1 {coin}"]
Output:
$48000 for 1 Bitcoin
$2585 for 1 Ethereum
$2 for 1 Cardano
Here, the zip
function takes in two lists and provides an iterable that gives a tuple of the corresponding elements of both the lists as we loop over it.