Python Forum
Is it possible to avoid 2 loops inside another loop?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is it possible to avoid 2 loops inside another loop?
#1
Assume I have the following folders inside a folder called Repository.
  • Space
  • Landscape\Bridges

I want to go though each folder under the Repository and before I work with the folders, I need to make sure they meet certain specifications:
  • It is in fact a folder
  • The folder isn't empty
  • The folder doesn't contain a sub folder.

Under the following specifications the Landscape\Bridges folder would not be processed, it will be ignored.

Here is my code that does this:

def rename_images(self):

     for folder in self._root_source.iterdir():

         if self._folder_is_valid(folder=folder): 
             _rename_and_move_images(folder=path, destination=destination, start=start)


 def _folder_is_valid(self, folder) -> bool:

    return (folder.is_dir() 
            and self._get_number_of_items_in(folder=folder)
            and not self._if_subdirectories_contain_directories(folder=folder))


 def _if_subdirectories_contain_directories(self, folder : Path) -> int:
     folder_lst = [sub_folder for sub_folder in folder.iterdir() if sub_folder.is_dir()]


 def _rename_and_move_images(self, folder: Path, destination: Path, start: int):

     for number, image in enumerate(folder.iterdir(), start=start):
        # Loop, rename and move the file.
I have a for loop, and inside I have an if statement that calls self._if_subdirectories_contain_directories(folder=folder) which uses a for loop to determine if any subfolders exist. This means a for loop inside another for loop.

When that validation is done, I call def _rename_and_move_images(self, folder: Path, destination: Path, start: int). Which uses a for loop to rename and move the images inside the valid folder.

Simply put, I have a for loop that starts another for loop, and when that's done, I start another one.

I'm aware that nested for loops are bad practice, so is it possible to clean this up so that I don't use nested for loops?
Reply
#2
(Nov-26-2019, 06:03 PM)SvetlanaofVodianova Wrote: I'm aware that nested for loops are bad practice

I'm not aware of this. Nested loops are a common tool in programming. They're only a problem if one of the loops is a problem, and loops can be a problem without nesting them. I don't see any problems with the loops you have in your code.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
You could simplify things with os.walk()
import os

def _rename_images(self):
    for folder in self._valid_folders():
        self._rename_and_move_images(...)

def _valid_folders(self):
    for folder in self._subfolders(self._root_source):
        dirnames, filenames = next(os.walk(folder))[1:]
        if filenames and not dirnames: # folder not empty and without subfolder
            yield folder

def _subfolders(self, folder):
    for dirname in next(os.walk(folder))[1]:
        yield folder / dirname
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable definitions inside loop / could be better? gugarciap 2 373 Jan-09-2024, 11:11 PM
Last Post: deanhystad
  How to create a variable only for use inside the scope of a while loop? Radical 10 1,524 Nov-07-2023, 09:49 AM
Last Post: buran
  Help adding a loop inside a loop Extra 31 4,333 Oct-23-2022, 12:16 AM
Last Post: Extra
  Nested for loops - help with iterating a variable outside of the main loop dm222 4 1,532 Aug-17-2022, 10:17 PM
Last Post: deanhystad
  Adding to the dictionary inside the for-loop - weird behaviour InputOutput007 5 2,651 Jan-21-2021, 02:21 PM
Last Post: InputOutput007
  why print('\n') produced 2 new lines instead of 1 - Located inside a FOR loop JulyFire 2 2,466 Jan-10-2021, 01:50 AM
Last Post: JulyFire
  Creating a variables inside FOR loop zazas321 5 4,039 Sep-16-2020, 04:42 PM
Last Post: Naheed
  How to to tie the execution of one process to another inside a loop in Python ignorant_wanderer 0 2,018 Jul-11-2020, 03:44 AM
Last Post: ignorant_wanderer
  Updating a matrix in a time interval inside a for loop vp1989 4 2,847 May-17-2020, 07:15 PM
Last Post: vp1989
  Loop inside loop inside loop L0RTK1PAN1DZ3 4 2,199 Mar-16-2020, 10:44 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020