How to copy or clone list in Python

Lists are ordered collection object type. Lists can contain any sort of object: numbers, strings, tuple,dictionary and even other lists. Lists are mutable objects.

How to copy or clone list in Python

1. Create List

>>> L=['Python','R','SAS','SPSS','Java','Data Analytics',[1,2,3,4],10,3.14]

2.Clone using list() function

>>> Techs=list(L) >>> type(Techs) >>> Techs ['Python', 'R', 'SAS', 'SPSS', 'Java', 'Data Analytics', [1, 2, 3, 4], 10, 3.14]

>>> Techs==L ##Compare both are same or not.
True

3. Clone using Slice

>>> Techs1=L[:] >>> Techs1==Techs True >>> Techs1==L #Compare both lists are same or not. True

4. Generic way to clone a list.

>>> import copy >>> new_list=copy.copy(L) >>> new_list ['Python', 'R', 'SAS', 'SPSS', 'Java', 'Data Analytics', [1, 2, 3, 4], 10, 3.14] >>> type(new_list) >>> new_list==L ##Compare both lists are same or not. True >>>

Responses are currently closed, but you can trackback from your own site.

Comments are closed.

Powered by k2schools
%d bloggers like this: