so ...
the [:] on the LHS uses a whole list slice assignment to update the existing reference and avoid assigning a new reference. and each dirlist reference i get from each step of the generator i get from os.walk() is kept internal in the generator and subsequently used, as modified in-place, to descend in the tree walk.
so ...
or i could do ...
the [:] on the LHS uses a whole list slice assignment to update the existing reference and avoid assigning a new reference. and each dirlist reference i get from each step of the generator i get from os.walk() is kept internal in the generator and subsequently used, as modified in-place, to descend in the tree walk.
(Jan-09-2018, 05:09 PM)wavic Wrote: Well, if I want to traverse my /home/$USER directory and I want to exclude Music and Video I can just remove them from the list:
for root, dirs, files in os.walk('/home/victor/'): dirs = [item for item in dirs[:] if item not in ('Music', 'Video)]It's completely safe to do that and os.walk will not going through these directories.
so ...
for root, dirs, files in os.walk('/home/victor/'): dirs[:] = [item for item in dirs if item not in ('Music', 'Video)]it builds a new list without those 2 names, which is thus 2 elements shorter, and is copied (because of the slice reference on the LHS) into the whole list (because the slice reference is a whole reference) making that list to now be 2 elements shorter.
or i could do ...
for root, dirs, files in os.walk('/home/victor/'): dirs[:] = sorted([item for item in dirs if item not in ('Music', 'Video)])
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.