zud
zud

Reputation: 105

Python list.remove() removes items from another list

I want to remove the folders containing 'Done' in the folder name. Here is my code

import os
mainPath = os.getcwd() + "/MyFolder/"
folderList = os.listdir(mainPath)
tempList = folderList     # so that I can iterate while using remove()
print len(tempList)
print len(folderList)
for folder in tempList:
    if 'Done' in folder:
        folderList.remove(folder)
print len(tempList)       # expected: Not to change
print len(folderList)

The output I get is:
26
26
22
22

I do not understand why it is deleting items from testList. Shouldn't it delete only from folderList?

Upvotes: 0

Views: 58

Answers (1)

Adam Smith
Adam Smith

Reputation: 54183

You're making the lists point to the same thing. use copy.deepcopy

Essentially when you do tempList = folderList it makes the two lists point to the same thing. If you want two copies of the same list that you can operate on separately you need to do:

import copy

tempList = copy.deepcopy(folderList)

If you know that all the items in your list are immutable, you can do tempList = folderList[:], but deepcopy is safer.

There's a wealth of information on this related question

Upvotes: 3

Related Questions