+91 81900 98289

Copy Lists

This Copy Lists lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

Assigning a list to a second name shares one list. copy builds a new list with the same items.

A slice of the whole list, skills[:], is another way to copy. Both are shallow: a list stored inside is still shared.

Example 1: Start here

fresh stays [Python, SQL]. skills and alias both gain Git.

skills = ["Python", "SQL"] # a list; the values stay in this order alias = skills # another name for the same value fresh = skills.copy() # a separate copy alias.append("Git") # add one item at the end of the list print(skills) print(fresh)

Example 2: Copy before you change

copy gives you a separate list. Appending to one does not change the other.

scores = [70, 80] # a list; the values stay in this order backup = scores.copy() # a separate copy scores.append(90) # add one item at the end of the list print(backup) print(scores)

Example 3: A slice copy

scores[:] is another way to copy the whole list.

scores = [70, 80, 90] # a list; the values stay in this order backup = scores[:] # a separate copy print(backup)

Example 4: Two names, one list

Assignment does not copy. Both names see the appended 90.

scores = [70, 80] # a list; the values stay in this order alias = scores # another name for the same value alias.append(90) # add one item at the end of the list print(scores)
fresh stays [Python, SQL]. skills and alias both gain Git.
Call Now 81900 98289