Pythonic way to assign variable before entering for loop

79 views Asked by At

I am iterating over a list of strings and matching whether the target version of last string matches current version of present string.

My solution to this problem is:

regex_pattern = r"^(\w+)-to-(\w+)\.bat$"
script_list = ["v1-to-v2.bat", "v2-to-v3.bat", "v3-to-v4.bat", "v5-to-v6.bat", "v6-to-v7.bat"]
first_script_match = re.match(regex_pattern, script_list[0])
temp_script = first_script_match.group(0)
temp_version = first_script_match.group(2)
for script in script_list[1:]:
    script_match = re.match(regex_pattern, script)
    if (from_version := script_match.group(1)) != temp_version:
        print(
            f"Target version {temp_version} of last script {temp_script} does not "
            f"match current version {from_version} of current script {script}"
        )
    temp_script = script_match.group(0)
    temp_version = script_match.group(2)

which is similar to the accepted answer of this question.

I was wondering if there is a more pythonic solution to this problem that does not pollute the module's namespace as much. I know about the walrus operator that has been introduced in Python 3.8 for the same purpose, but I'm not sure if I can use it in a for loop.

0

There are 0 answers