![]() |
|
[Tut] How to Initialize Multiple Variables to the Same Value in Python? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Initialize Multiple Variables to the Same Value in Python? (/thread-99647.html) |
[Tut] How to Initialize Multiple Variables to the Same Value in Python? - xSicKxBot - 06-30-2022 How to Initialize Multiple Variables to the Same Value in Python? Rate this post Summary: To initialize multiple variables to the same value in Python you can use one of the following approaches:
This article will guide you through the ways of assigning multiple variables with the same value in Python. Without further delay, let us dive into the solutions right away. [b]Method 1: Using Chained Equalities[/b] You can use chained equalities to declare the variables and then assign them the required value. Code: Syntax: variable_1 = variable_2 = variable_3 = valueCode: Code: x = y = z = 100
print(x)
print(y)
print(z)
print("All variables point to the same memory location:")
print(id(x))
print(id(y))
print(id(z))Output: Code: 100
100
100
All variables point to the same memory location:
3076786312656
3076786312656
3076786312656It is evident from the above output that each variable has been assigned the same value and each of them point to the same memory location. [b]Method 2: Using dict.fromkeys[/b] Approach: Use the Code: dict.fromkeys(variable_list, val)Code: valCode: variable_listCode: Code: variable_list = ["x", "y", "z"]
d = dict.fromkeys(variable_list, 100)
for i in d: print(f'{i} = {d[i]}') print(f'ID of {i} = {id(i)}')Output: Code: x = 100
ID of x = 2577372054896
y = 100
ID of y = 2577372693360
z = 100
ID of z = 2577380842864Discussion: It is evident from the above output that each variable assigned holds the same value. However, each variable occupies a different memory location. This is on account that each variable acts as a key of the dictionary and every key in a dictionary is unique. Thus, changes to a particular variable will not affect another variable as shown below: Code: variable_list = ["x", "y", "z"]
d = dict.fromkeys(variable_list, 100)
print("Changing one of the variables: ")
d['x'] = 200
print(d)Output: Code: {'x': 200, 'y': 100, 'z': 100}Conceptual Read: Code: fromkeys()Syntax: Code: dict.fromkeys(keys, value) keys is a required parameter that represents an iterable containing the keys of the new dictionary. value is an optional parameter that represents the values for all the keys in the new dictionary. By default, it is Code: NoneExample: Code: k = ('key_1', 'key_2', 'key_3')
my_dictionary = dict.fromkeys(k, 0)
print(my_dictionary) # OUTPUT: {'key_1': 0, 'key_2': 0, 'key_3': 0}Let’s address a frequently asked question that troubles many coders. Problem: I tried to use multiple assignment as show below to initialize variables, but I got confused by the behavior, I expect to reassign the values list separately, I mean b[0] and c[0] equal 0 as before. Code: a=b=c=[0,3,5]
a[0]=1
print(a)
print(b)
print(c)Output: Code: a = b = c = [0, 3, 5]
a[0] = 1
print(a)
print(b)
print(c)But, why does the following assignment lead to a different behaviour? Code: a = b = c = 5
a = 3
print(a)
print(b)
print(c)Output: Code: 3
5
5Question Source: StackOverflow [b]Solution[/b] Remember that everything in Python is treated as an object. So, when you chain multiple variables as in the above case all of them refer to the same object. This means, Code: aCode: bCode: c![]() Thus, in the first case when you make a change at a certain index of variable a, i.e, a[0] = 1. This means you are making the changes to the same object that also has the names b and c. Thus the changes are reflected for b and c both along with a. Verification: Code: a = b = c = [1, 2, 3]
print(a[0] is b[0]) # TrueTo create a new object and assign it, you must use the copy module as shown below: Code: import copy
a = [1, 2, 3]
b = copy.deepcopy(a)
c = copy.deepcopy(a)
a[0] = 5
print(a)
print(b)
print(c)Output: Code: [5, 2, 3]
[1, 2, 3]
[1, 2, 3]However, in the second case you are rebinding a different value to the variable Code: aFollow the given illustration to visualize what’s happening in this case: ![]() Verification: Code: a = b = c = 5
a = 3
print(a is b)
print(id(a))
print(id(b))
print(id(c))Output: Code: False
2329408334192
2329408334256
2329408334256It is evident that after rebinding a new value to the variable Code: aCode: aCode: aCode: bCode: cPython One-Liners Book: Master the Single Line First! Python programmers will improve their computer science skills with these useful one-liners. ![]() Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert. The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line. Get your Python One-Liners on Amazon!! |