-1

I'm facing a situation where I can't crack the logic behind.

I have a piece of code that does

user_id = user_email = []
for id, email in users: 
    # users is a tuple of tuples that looks like ((a,b),(c,d)...)
    user_id.append(id)
    user_email.append(email)

When I check the result, I found that user_id == user_email

When I assign them separately, I can correctly get the id's and email's, instead of two identical lists that contain both id's and email's

I'm just wondering what's the logic behind the double assign and what causes this phenomenon to happen.

JChao
  • 2,178
  • 5
  • 35
  • 65
  • 4
    You are creating exactly one list object (`[]`) whose reference you're assigning to two variables. Both variables point at the same list. – deceze May 25 '16 at 00:47
  • 2
    `user_id, user_email = zip(*users)` – Karoly Horvath May 25 '16 at 00:51
  • yea I'm not looking for correct way to do this. I was just doing a really simple test so I didn't bother the performance. I just found out about this and want to know what exactly is going on – JChao May 25 '16 at 00:57
  • Seriously woeth your time to check the SO answer I link in my answer. It is very informative, in depth, keeps it light with rapper and zombie examples. – EoinS May 25 '16 at 00:59
  • 1
    This is merely another variant of [How to clone or copy a list in Python?](http://stackoverflow.com/q/2612802). You have **one** list object with two names, not two separate lists. – Martijn Pieters May 25 '16 at 01:01

2 Answers2

2

When you set

user_id = user_email = []

You link user_id and user_email to one list. When the list changes both variables change.

Set these variables separately.

User_id = []
User_email = []

This can be confusing if coming from language like C. Think of a variable in python as a name not a variable.

This is so incredibly helpful

Community
  • 1
  • 1
EoinS
  • 5,405
  • 1
  • 19
  • 32
1

Here's an explanation of what is going on:

>>> a = b = []
>>> c = []
>>> id(a)
41002688
>>> id(b)
41002688
>>> id(c)
41023328

Notice that a and b both have the same ID, but c has a different one - that's because a and b are pointing to the same list.

Random Davis
  • 6,662
  • 4
  • 14
  • 24