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
639 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 aryya
• 7,460 points
10,636 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
• 58,100 points
11,663 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 aryya
• 7,460 points
3,194 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, 2019 in Python by Junaid
2,184 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,390 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
3,991 views
+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
1,285 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
35,343 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP