> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Hoist Loop from If

#### Sourcery refactoring id: `hoist-loop-from-if`

#### Description:

Moves loops that occur in all cases of an `if` statement outside of the
conditional

#### Before:

```python
def sing_song(self):
    if style == 1:
        while thing_true():
            do_x()
    elif style == 2:
        while thing_true():
            do_y()
    elif style == 3:
        while thing_true():
            do_z()
```

#### After:

```python
def sing_song(self):
    while thing_true():
        if style == 1:
            do_x()
        elif style == 2:
            do_y()
        elif style == 3:
            do_z()
```

#### Explanation:

Where the same `for` or `while` loop is defined in all branches of a
conditional, the code can be considerably shortened and clarified by hoisting.
By moving the loop outside, duplication is removed and the code becomes much
clearer.
