We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

How do I copy an object in Python?

Try copy.copy or copy.deepcopy for the general case. Not all objects can be copied, but most can.

import copy

newobj = copy.copy(oldobj) # shallow copy
newobj = copy.deepcopy(oldobj) # deep (recursive) copy

Some objects can be copied more easily. Dictionaries have a copy method:

newdict = olddict.copy()

Sequences can be copied by slicing:

new_list = L[:]

You can also use the list, tuple, dict, and set functions to copy the corresponding objects, and to convert between different sequence types:

new_list = list(L) # copy
new_dict = dict(olddict) # copy

new_set = set(L) # convert list to set
new_tuple = tuple(L) # convert list to tuple

CATEGORY: programming