0

I wanna copy a list into new list here my code which is not works:

l = list(range(0,101,2))
n = []

def change(l):
    for i in range (len(l)):
        k = l.copy()
        n[k] = l[:] 


print (l)
print (n)

I wanna copy the l list into the n list,but it not works. Thanks the help in advance.

DanyJ
  • 51
  • 4

3 Answers3

1
>>>l = range(0,101,2)
>>>n = [x for x in l]
florex
  • 943
  • 7
  • 9
0

You could use https://docs.python.org/2/library/copy.html

import copy
n = copy.copy(l)

To avoid the following problem with n = l:

l = list(range(0,21,2))
n = []
n = l
l.append(1000)
print (n) #=> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 1000]
iGian
  • 11,023
  • 3
  • 21
  • 36
0

One of the ways to copy the list without using any module is n = l[:]:

l = list(range(0,101,2)) # get list of even values from 0 to 100
n = l[:]                 # copy data from l to n
print (l)                # check data of l
print(n)                 # check data of n
l.pop()                  # remove last element from l
print(l)                 # It prints only 0 to 98
print(n)                 # It prints from 0 to 100 (can you see here, changing l doesnot impact n)

Now if you use n = l directly then any change in l will change the value in n, check below code:

l = list(range(0,101,2))

n=l
print (l)                # check data of l
print(n)                 # check data of n
l.pop()                  # remove last element from l
print(l)                 # It prints from 0 to 98
print(n)                 # It prints from 0 to 98
Akash Swain
  • 520
  • 3
  • 13