0

I'm getting some branches from git using a bash command via subprocess.check_outpupt, decoding it, stripping it and then splitting it into a list.

I'm then iterating over the list to check which branches don't match the requirements and if that's the case, removing them from the list. For some reason though, it's not working as expected.

#Comes back as a bytes object with newlines after each branch name
git = subprocess.check_output(["git", "branch", "-r"])

branches = git.decode("utf-8").replace("origin/", "").strip("\n").split()

for branch in branches:
   if "LIVE" not in branch:
      branches.remove(branch)

print(branches)

At the end I'm expecting branches to come back as an empty list because I know none of the branches have "LIVE" in them so should be removed from the list. However, the list still comes back with 1/2 elements each time and I'm not sure why.

1 Answers1

2

The iterator really just wraps around indexing in the list. Let's take an example where you have a list [1, 2, 3] and it's currently on the first element:

[1, 2, 3]
 ^

When you remove it then continue the loop, the iterator will advance to the second element, but the list will be shifted to the left:

[2, 3]
    ^

So, the iterator essentially skipped an item. You should just use the filtering that list comprehensions have to avoid this issue:

branches = [branch in branches if "LIVE" not in branch]
Aplet123
  • 33,825
  • 1
  • 29
  • 55