To create a variable number of variables in Python, either use a dictionary or a namedtuple.
Problem: How can you store variable number of variables in your Python code?
Example: Consider that there is a requirement wherein you have to store the specifications of a product in a single variable which includes a variable number of variables that are used to store different parameters of the product. For example, we want to store the parameters like brand name, model, and year of manufacture inside another variable named Product. The diagram below shall explain the problem in detail.
This is just an example scenario that shall be used to demonstrate the solutions to our problem statement.
Method 1: Using Python Dictionaries
The easiest way to accomplish our task is to make use of Python dictionaries. A dictionary is a collection that lets you store data in the form of key and value pairs where the keys are used to represent the variables while the value represents the values to be stored in the variables. To have a better grip on the concept of dictionaries, I highly recommend you have a look at this article.
The following code will help you understand the usage of dictionaries to store a variable number of variables (Please read the comments to understand the code better) :
product = { "brand": 'Apple', "model": 'iPhone 11 Pro', "year": '2019' } print(product) # If want to access a particular variable, for eg, Brand Name then use: print("Product Brand is : ", product["brand"]) # If you want to loop through the variables and their corresponding values then use: for x, y in product.items(): print(x, ":", y)
Output:
{'brand': 'Apple', 'model': 'iPhone 11 Pro', 'year': '2019'} Product Brand is : Apple brand : Apple model : iPhone 11 Pro year : 2019
Before jumping into the next solution let us discuss a different scenario where you have to store variable brands of a product along with their specifications. Take a look at the diagram below to visualize the scenario we shall be discussing next.
This might look like a complex scenario, however with the use of python dictionaries even such situations can be handled with ease. The program given below demonstrates how you can deal with such situations:
products = { "Apple": { "Brand": "Apple", "Model": "iPhone 11 Pro", "Year": "2019" }, "Samsung": { "Brand": "Samsung", "Model": "Galaxy Note 20 Ultra 5G", "Year": "2020" }, "Nokia": { "Brand": "Nokia", "Model": "Nokia C3", "Year": "2020" } } for x, y in products.items(): print(x, ":", y)
Output:
Apple : {'Brand': 'Apple', 'Model': 'iPhone 11 Pro', 'Year': '2019'} Samsung : {'Brand': 'Samsung', 'Model': 'Galaxy Note 20 Ultra 5G', 'Year': '2020'} Nokia : {'Brand': 'Nokia', 'Model': 'Nokia C3', 'Year': '2020'}
Try it yourself in the interactive code shell:
Exercise: Run the code. Does the output match?
Method 2: Using getattr()
Another way of storing a variable number of variables can be accomplished using a built-in method called getattr()
. The getattr()
function is used to return the value of a specified attribute of an object. Therefore you can store the values in the variables and encapsulate them in a class and then retrieve the desired value using the getattr()
function.
The following code demonstrates the above concept:
class Product: brand = "Apple" model = "iPhone 11 Pro" year = 2020 x = getattr(Product, 'model') print("brand:", x)
Output:
brand: iPhone 11 Pro
Method 3: Using namedtuple
“namedtuple()
” is a type of container in Python just like dictionaries. It is present within the collections module. Just like dictionaries, namedtuples
also consist of key-value pairs, however, in the case of namedtuple()
you can access from both keys as well as the values, which is not the case with dictionaries where you must access the value from the key. Unlike dictionaries namedtuple()
is an ordered container and you can access its values using the index numbers.
Let us have a look at the following code to understand how namedtuple()
container can be used to store a variable number of variables:
import collections # declaring the namedtuple() Product = collections.namedtuple('Apple', ['Brand', 'Model', 'Year']) # Passing the values prod = Product('Apple', 'iPhone 11 Pro', '2020') # Accessing the values using different ways print("Brand: ", prod[0]) print("Model: ", prod.Model) print("Year: ", getattr(prod, 'Year'))
Output:
Brand: Apple Model: iPhone 11 Pro Year: 2020
Before wrapping up this article, there is a little concept I would like to touch upon which might be instrumental in dealing with situations of variable number of variables.
Method 4: Using Arbitrary Arguments (*args)
In Python, we can pass a variable number of arguments to a function using the special symbol *args
. Therefore we can make use of the * symbol before a parameter name in the function definition to pass a variable number of arguments to the function.
Let us have a look at the following code to understand the usage of *args
:
def my_function(*k): print("Brand: ", k[0]) print("Model: ", k[1]) print("Year: ", k[0]) my_function("Apple", "iPhone 11 Pro", "2020")
Output:
Brand: Apple Model: iPhone 11 Pro Year: Apple
Conclusion
Thus from the solutions discussed above, we can safely say that python offers a plethora of options to create and store values in a variable number of variables. I hope you found this article helpful and it helps you to create a variable number of variables in Python with ease.
Stay tuned for more interesting stuff in the future!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.