• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
 Welcome You have to register before you can post on our site. Username: Password: Remember me

 Discord Widget

 Latest Threads [Tut] 3 Simple Steps to Convert calendar... Last Post: xSicKxBot Today 12:58 AM » Replies: 0 » Views: 0 [Tut] Add Google reCaptcha V3 Example wi... Last Post: xSicKxBot Today 12:58 AM » Replies: 0 » Views: 0 (Free Game Key) Cook, Serve, Delicious! ... Last Post: xSicKxBot Today 12:58 AM » Replies: 0 » Views: 0 PC - Frogun Last Post: xSicKxBot Today 12:57 AM » Replies: 0 » Views: 0 [Tut] How to Sort Words Alphabetically i... Last Post: xSicKxBot Yesterday 05:51 AM » Replies: 0 » Views: 0 PC - The Sims 4: High School Years Last Post: xSicKxBot Yesterday 05:51 AM » Replies: 0 » Views: 0 News - Edgar Allan Poe Horror Biopic Rav... Last Post: xSicKxBot Yesterday 05:51 AM » Replies: 0 » Views: 0 [Oracle Blog] Announcing GraalVM Enterpr... Last Post: xSicKxBot 08-10-2022 12:05 PM » Replies: 0 » Views: 0 [Tut] Best Solidity Linter Last Post: xSicKxBot 08-10-2022 12:05 PM » Replies: 0 » Views: 0 [Tut] JavaScript Autocomplete TextBox (a... Last Post: xSicKxBot 08-10-2022 12:05 PM » Replies: 0 » Views: 0

[Tut] How to Initialize Multiple Variables to the Same Value in Python?

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:

• Use chained equalities as: `var_1 = var_2 = value`
• Use `dict.fromkeys`

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.

## Method 1: Using Chained Equalities

You can use chained equalities to declare the variables and then assign them the required value.

`Syntax: variable_1 = variable_2 = variable_3 = value `

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:

``````100
100
100
All variables point to the same memory location:
3076786312656
3076786312656
3076786312656``````

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.

## Method 2: Using dict.fromkeys

Approach: Use the `dict.fromkeys(variable_list, val)` method to set a specific value (`val`) to a list of variables (`variable_list`).

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:

``````x = 100
ID of x = 2577372054896
y = 100
ID of y = 2577372693360
z = 100
ID of z = 2577380842864``````

Discussion: 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:

```variable_list = ["x", "y", "z"]
d = dict.fromkeys(variable_list, 100)
print("Changing one of the variables: ")
d['x'] = 200
print(d)```

Output:

``{'x': 200, 'y': 100, 'z': 100}``

`fromkeys()` is a dictionary method that returns a dictionary based on specified keys and values passed within it as parameters.

Syntax: `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 `None`.

Example:

```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}```

## Related Question

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.

```a=b=c=[0,3,5]
a[0]=1
print(a)
print(b)

Output:

``````a = b = c = [0, 3, 5]
a[0] = 1
print(a)
print(b)
``````

But, why does the following assignment lead to a different behaviour?

```a = b = c = 5
a = 3
print(a)
print(b)

Output:

``````3
5
5``````

Question Source: StackOverflow

### Solution

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, `a` , `b` and `c` are not different variables with same values rather they are different names given to the same object.

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:

```a = b = c = [1, 2, 3]
print(a[0] is b[0]) # True```

To create a new object and assign it, you must use the copy module as shown below:

```import copy
a = [1, 2, 3]
b = copy.deepcopy(a)
c = copy.deepcopy(a)
a[0] = 5
print(a)
print(b)

Output:

``````[5, 2, 3]
[1, 2, 3]
[1, 2, 3]``````

However, in the second case you are rebinding a different value to the variable `a`. 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.

Follow the given illustration to visualize what’s happening in this case:

Verification:

```a = b = c = 5
a = 3
print(a is b)
print(id(a))
print(id(b))

Output:

``````False
2329408334192
2329408334256
2329408334256``````

It is evident that after rebinding a new value to the variable `a`, it points to a different memory location, hence it now refers to a different object. Thus, changing the value of `a` in this case means we are creating a new object without touching the previously created object that was being referred by `a`, `b` and `c`.

## Python 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 comprehensionslicinglambda functionsregular expressionsmap and reduce functions, and slice assignments.

You’ll also learn how to:

• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
• Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
• Create more advanced regular expressions using grouping and named groupsnegative lookaheadsescaped characterswhitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
• Understand a wide range of computer science topics, including anagramspalindromessupersetspermutationsfactorialsprime numbersFibonacci numbers, obfuscationsearching, and algorithmic sorting

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!!

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

 Users browsing this thread: 1 Guest(s)

𝚂̷𝚒̷𝚌̷𝚔̷𝙶̷𝚊̷𝚖̷𝚒̷𝚗̷𝚐̷ 𝙷̷𝚘̷𝚖̷𝚎̷