Sunday 20 December 2020

Python: Copy entire list

By creating a slice on existing list, you can copy entire list.

 

Syntax

new_list = existing_list[:]

 

Example

my_hobbies_1 = ["Playing cricket", "Blogging"]

my_hobbies_2 = my_hobbies_1[:]

 

list_copy.py

my_hobbies_1 = ["Playing cricket", "Blogging"]

my_hobbies_2 = my_hobbies_1[:]

print(f"my_hobbies_1 :{my_hobbies_1}")
print(f"my_hobbies_2 :{my_hobbies_2}")

 

Output

 

$ python3 list_copy.py 
my_hobbies_1 :['Playing cricket', 'Blogging']
my_hobbies_2 :['Playing cricket', 'Blogging']

 

When you copy using slice notation, it copies the items in exist list to a completely new list. Let’s confirm the same with below example.

 

list_copy2.py

my_hobbies_1 = ["Playing cricket", "Blogging"]

my_hobbies_2 = my_hobbies_1[:]

print(f"my_hobbies_1 :{my_hobbies_1}")
print(f"my_hobbies_2 :{my_hobbies_2}")

print("\nAdd new hobbies to my_hobbies_1 and my_hobbies_2")

my_hobbies_1.append("watching movies")
my_hobbies_1.append("trekking")
my_hobbies_2.append("reading books")

print(f"\nmy_hobbies_1 :{my_hobbies_1}")
print(f"my_hobbies_2 :{my_hobbies_2}")

 

Output

$ python3 list_copy2.py 
my_hobbies_1 :['Playing cricket', 'Blogging']
my_hobbies_2 :['Playing cricket', 'Blogging']

Add new hobbies to my_hobbies_1 and my_hobbies_2

my_hobbies_1 :['Playing cricket', 'Blogging', 'watching movies', 'trekking']
my_hobbies_2 :['Playing cricket', 'Blogging', 'reading books']

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment