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
17 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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,320 points
761 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,100 points
98 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,320 points
38 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 5 days ago in Python by Junaid
6 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 920 points
18 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
64 views
+4 votes
6 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
1,729 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.