1

I have program in which I loop over a list of subfolders (dir_list) which is obtained using os.walk. Now, I loop over the full list using enumerate, as follows:

for day_index, day_folder in enumerate(dir_list[:]):

Now, I'd like to test the code within this loop on the last element (without running the whole loop, because the program is quite large). So I do the following:

for day_index, day_folder in enumerate(dir_list[-1]):

However, now that dir_list is a single element enumerate behaves differently and starts to iterate through the single element, which happens to be a string, resulting in day_folder becoming the first element of the string. This is of course not what I want to happen. But I understand why it is happening.

How can I run this loop - for testing purposes - just on the last element of the list (my last subfolder). I don't want to change my code by removing the for loop, and I need to retain the counter (day_index).

Flimzy
  • 68,325
  • 15
  • 126
  • 165

1 Answers1

2

How about that:

for day_index, day_folder in enumerate(dir_list[-1:]):

This is simple list slicing.

Artsiom Praneuski
  • 2,062
  • 13
  • 21