Why can't I have two different link objects? I create _link and _link2 as empty objects.

When I do this:
_link2 = _link,

it just creates alias _link2 to link object. Same object have 2 aliases _link2 and _link. Is there a way to copy the content of _link to _link2?

When I do this: _link2 = _link2.append("adding stuff")
why does _link2 become "None"

My code:

_link = []
site_url = "http://www.mysite.com/"
_link.append(site_url)
_link2 = []
_link2 = _link
_link2 = _link2.append("adding stuff")

print _link
print _link2

Output:


None

Recommended Answers

All 3 Replies

The problem is that Python does assignment by reference. So the line

_link2 = _link

operates by making _link2 and _link both point to the same object. Change one, and you've changed them both.

If you want to copy the contents, do a slice:

_link2 = _link[:]

The operation on the left returns an entire copy of _link, which then gets assigned to _link2.

Jeff

Be careful with a slice copy ...

old_list = [1, [2, 3,[4]], 5]
new_list = old_list[:]

# now change old_list
old_list[1][0] = 1111
 
print old_list  # [1, [1111, 3, [4]], 5]
print new_list  # [1, [1111, 3, [4]], 5]  oops!

If you want to make a copy of a list, even a deeply nested list, you best use the module copy ...

import copy
 
old_list = [1, [2, 3,[4]], 5]
new_list = copy.deepcopy(old_list)

# now change old_list
old_list[1][0] = 1111
 
print old_list  # [1, [1111, 3, [4]], 5]
print new_list  # [1, [2, 3, [4]], 5]  now it works

That's awkward...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.