Variables in Python

0 votes
Please explain how variable assignment happens in python. I come from a C background and I understand that variables work differently in python.
Apr 26, 2018 in Python by cguy
33 views

1 answer to this question.

0 votes

Variables in python work differently than they do in C. While in C, a statement like "x = 5;" means that the value 5 is stored in a memory position labeled as x, in Python, variables are references to objects in which values are stored. So, a statement like "x = 5" in python implies that x is a reference to an object containing the value 5.

One way how this leads to different outcomes is to take the example of variable reassignment. 

>>> x = [1, 2, 3]
>>> y = x
>>> x.append(4)
>>> x
[1, 2, 3, 4]
>>> y
[1, 2, 3, 4]
>>> 

As you can see in the above code, if there are two variables i.e., two references to a value, any mutation to the value in-place leads to the change being reflected in both the variables.

answered Apr 26, 2018 by Nietzsche's daemon
• 4,260 points

Related Questions In Python

0 votes
1 answer

How do you get the logical xor of two variables in Python?

If you're already normalizing the inputs to ...READ MORE

answered May 29, 2018 in Python by ariaholic
• 7,340 points
4,197 views
0 votes
1 answer

How do you get the logical xor of two variables in Python?

What i found is that you can use ...READ MORE

answered Aug 10, 2018 in Python by Priyaj
• 56,960 points
1,153 views
0 votes
1 answer

How can I prevent or alter access to class variables in Python?

The ActiveState solution that Pynt references makes instances of ...READ MORE

answered Dec 5, 2018 in Python by ariaholic
• 7,340 points
75 views
0 votes
1 answer

Is there a way to list out in-built variables and functions of Python?

The in-built variables and functions are defined ...READ MORE

answered May 14 in Python by Junaid
50 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 401 views
+4 votes
6 answers
+4 votes
6 answers

Substring search in Python

Use the "in" operator in python" if "substring" ...READ MORE

answered Apr 13, 2018 in Python by Nietzsche's daemon
• 4,260 points
133 views
+4 votes
7 answers

Splitting a List into chunks in Python

Here's a generator that yields the chunks ...READ MORE

answered Apr 13, 2018 in Python by Nietzsche's daemon
• 4,260 points
8,679 views