Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Initialize Multiple Variables to the Same Value in Python?

#1
How to Initialize Multiple Variables to the Same Value in Python?

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;438906&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;0&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;0&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;0\/5 - (0 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;0&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 0px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> <span class="kksr-muted">Rate this post</span> </div>
</div>
<p><strong>Summary: </strong>To initialize multiple variables to the same value in Python you can use one of the following approaches:</p>
<ul>
<li>Use chained equalities as: <code>var_1 = var_2 = value</code></li>
<li>Use <code>dict.fromkeys</code></li>
</ul>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<p>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.</p>
<h2><strong>Method 1: </strong>Using Chained Equalities</h2>
<p>You can use chained equalities to declare the variables and then assign them the required value.</p>
<pre class="wp-block-preformatted"><strong>Syntax: </strong>variable_1 = variable_2 = variable_3 = value </pre>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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))</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>100
100
100
All variables point to the same memory location:
3076786312656
3076786312656
3076786312656</code></pre>
<p>It 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.</p>
<h2><strong>Method 2: Using dict.fromkeys</strong></h2>
<p><strong>Approach: </strong>Use the <code>dict.fromkeys(variable_list, val)</code> method to set a specific value (<code>val</code>) to a list of variables (<code>variable_list</code>).</p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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)}')</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>x = 100
ID of x = 2577372054896
y = 100
ID of y = 2577372693360
z = 100
ID of z = 2577380842864</code></pre>
<p><strong>Discussion: </strong>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:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">variable_list = ["x", "y", "z"]
d = dict.fromkeys(variable_list, 100)
print("Changing one of the variables: ")
d['x'] = 200
print(d)</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>{'x': 200, 'y': 100, 'z': 100}</code></pre>
<p><strong>Conceptual Read:</strong></p>
<p class="has-base-background-color has-background"><code>fromkeys()</code> is a dictionary method that returns a dictionary based on specified keys and values passed within it as parameters.</p>
<p><strong>Syntax: </strong><code>dict.fromkeys(keys, value)</code><br /><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/27a1.png" alt="➡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>keys </strong>is a required parameter that represents an iterable containing the keys of the new dictionary.<br /><strong><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/27a1.png" alt="➡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> value </strong>is an optional parameter that represents the values for all the keys in the new dictionary. By default, it is <strong><code>None</code></strong>.</p>
<p><strong>Example:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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}</pre>
<h2>Related Question</h2>
<p>Let’s address a frequently asked question that troubles many coders.</p>
<p><strong>Problem: </strong>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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a=b=c=[0,3,5]
a[0]=1
print(a)
print(b)
print©</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>a = b = c = [0, 3, 5]
a[0] = 1
print(a)
print(b)
print©
</code></pre>
<p>But, why does the following assignment lead to a different behaviour?</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = b = c = 5
a = 3
print(a)
print(b)
print©</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>3
5
5</code></pre>
<p>Question Source: <strong><a href="https://stackoverflow.com/questions/16348815/python-assigning-multiple-variables-to-same-value-list-behavior?noredirect=1&amp;lq=1" target="_blank" rel="noreferrer noopener">StackOverflow</a></strong></p>
<h3><strong>Solution</strong></h3>
<p>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 data-enlighter-language="generic" class="EnlighterJSRAW">a</code> , <code data-enlighter-language="generic" class="EnlighterJSRAW">b</code> and <code data-enlighter-language="generic" class="EnlighterJSRAW">c</code> are not different variables with same values rather they are different names given to the same object. </p>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" width="570" height="305" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-169.png" alt="" class="wp-image-438998" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-169.png 570w, https://blog.finxter.com/wp-content/uplo...00x161.png 300w" sizes="(max-width: 570px) 100vw, 570px" /></figure>
<p> 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. </p>
<p><strong>Verification:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = b = c = [1, 2, 3]
print(a[0] is b[0]) # True</pre>
<p>To create a new object and assign it, you must use the copy module as shown below:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import copy
a = [1, 2, 3]
b = copy.deepcopy(a)
c = copy.deepcopy(a)
a[0] = 5
print(a)
print(b)
print©</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>[5, 2, 3]
[1, 2, 3]
[1, 2, 3]</code></pre>
<p>However, in the second case you are rebinding a different value to the variable <code>a</code>. This means, you are changing it in-place and that leads to a now pointing at a completely different value at a different location. Here, the value being changed is an interger and integers are immutable.</p>
<p>Follow the given illustration to visualize what’s happening in this case:</p>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" width="342" height="278" src="https://blog.finxter.com/wp-content/uploads/2022/06/img.gif" alt="" class="wp-image-439007" /></figure>
<p><strong>Verification:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = b = c = 5
a = 3
print(a is b)
print(id(a))
print(id(b))
print(id©)</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>False
2329408334192
2329408334256
2329408334256</code></pre>
<p>It is evident that after rebinding a new value to the variable <code>a</code>, it points to a different memory location, hence it now refers to a different object. Thus, changing the value of <code>a</code> in this case means we are creating a new object without touching the previously created object that was being referred by <code>a</code>, <code>b</code> and <code>c</code>.</p>
<h2>Python One-Liners Book: Master the Single Line First!</h2>
<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>
<div class="wp-block-image is-style-default">
<figure class="aligncenter is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noreferrer noopener"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg" alt="Python One-Liners" class="wp-image-10007" width="418" height="385" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x277.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x708.jpg 768w" sizes="(max-width: 418px) 100vw, 418px" /></a></figure>
</div>
<p><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener"><em>Python One-Liners</em>&nbsp;</a>will teach you how to read and write “one-liners”:&nbsp;<strong><em>concise statements of useful functionality packed into a single line of code.&nbsp;</em></strong>You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p>
<p>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.</p>
<p>Detailed explanations of one-liners introduce&nbsp;<strong><em>key computer science concepts&nbsp;</em></strong>and<strong><em>&nbsp;boost your coding and analytical skills</em></strong>. You’ll learn about advanced Python features such as&nbsp;<em><strong>list comprehension</strong></em>,&nbsp;<strong><em>slicing</em></strong>,&nbsp;<strong><em>lambda functions</em></strong>,&nbsp;<strong><em>regular expressions</em></strong>,&nbsp;<strong><em>map&nbsp;</em></strong>and&nbsp;<strong><em>reduce&nbsp;</em></strong>functions, and&nbsp;<strong><em>slice assignments</em></strong>.</p>
<p>You’ll also learn how to:</p>
<ul>
<li>Leverage data structures to&nbsp;<strong>solve real-world problems</strong>, like using Boolean indexing to find cities with above-average pollution</li>
<li>Use&nbsp;<strong>NumPy basics</strong>&nbsp;such as&nbsp;<em>array</em>,&nbsp;<em>shape</em>,&nbsp;<em>axis</em>,&nbsp;<em>type</em>,&nbsp;<em>broadcasting</em>,&nbsp;<em>advanced indexing</em>,&nbsp;<em>slicing</em>,&nbsp;<em>sorting</em>,&nbsp;<em>searching</em>,&nbsp;<em>aggregating</em>, and&nbsp;<em>statistics</em></li>
<li>Calculate basic&nbsp;<strong>statistics&nbsp;</strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning</li>
<li>Create more&nbsp;<strong>advanced regular expressions</strong>&nbsp;using&nbsp;<em>grouping&nbsp;</em>and&nbsp;<em>named groups</em>,&nbsp;<em>negative lookaheads</em>,&nbsp;<em>escaped characters</em>,&nbsp;<em>whitespaces, character sets</em>&nbsp;(and&nbsp;<em>negative characters sets</em>), and&nbsp;<em>greedy/nongreedy operators</em></li>
<li>Understand a wide range of&nbsp;<strong>computer science topics</strong>, including&nbsp;<em>anagrams</em>,&nbsp;<em>palindromes</em>,&nbsp;<em>supersets</em>,&nbsp;<em>permutations</em>,&nbsp;<em>factorials</em>,&nbsp;<em>prime numbers</em>,&nbsp;<em>Fibonacci&nbsp;</em>numbers,&nbsp;<em>obfuscation</em>,&nbsp;<em>searching</em>, and&nbsp;<em>algorithmic sorting</em></li>
</ul>
<p>By the end of the book, you’ll know how to&nbsp;<strong><em>write Python at its most refined</em></strong>, and create concise, beautiful pieces of “Python art” in merely a single line.</p>
<p><strong><a rel="noreferrer noopener" href="https://amzn.to/2WAYeJE" target="_blank"><em>Get your Python One-Liners on Amazon!!</em></a></strong></p>
</div>


https://www.sickgaming.net/blog/2022/06/...in-python/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016