How to loop through multiple variables in Python?

In this post, I describe how you can iterate/loop through multipe (two or more) variables at the same time in Python.

Iterate/loop through multiple variable using the zip function

In this post, I describe how to use the zip function to iterate/loop through multiple variables at the same time in python. In the below example I defined three variables with the same length, however, the zip function can handle any number of input variables:

var1 = [1,2,3]
var2 = [4,5,6]
var3 = [7,8,9]
for v1,v2,v3 in zip(var1, var2, var3):
     print(v1, v2, v3)

Result:

1 4 7
2 5 8
3 6 9

The great thing about the zip function is that it can be used with arrays, lists, and dictionaries of different lengths. This is demonstrated in the below code snippet:

var1 = [1,2,3]
var2 = [4,5,6]
var3 = [7,8]
for v1,v2,v3 in zip(var1, var2, var3):
     print(v1, v2, v3)

Result:

1 4 7
2 5 8

Demonstration

The video below demonstrates the described code snippets above:

How to split a string using multiple delimiters in Python?

In this post, I present two ways to split a string using multiple delimiters in Python.

Split a string using regular expression

Regular expressions are very powerful. It helps to get things done with a single function call. In the below example I use the split function from the re library to split a string along with multiple delimiters:

import re
str="this-is_an=example\string"
re.split(r"[-_=\\]", str)

Result:

['this', 'is', 'an', 'example', 'string']

In the above example, the string is split along the \, -, _, and = delimiters.

Replace other delimiters and split it

Another solution is to choose a single delimiter and replace all the other delimiters with the chosen one. After that, the split function can be used. I demonstrate this in the below example:

str="this-is_an=example\\string"
delimiters = ['-', '_', '=', '\\']
for i in range(1, len(delimiters)):
    str = str.replace(delimiters[i], delimiters[0])

str.split(delimiters[0])

Result:

['this', 'is', 'an', 'example', 'string']

In the above example, first I replaced all the delimiters with -, and then I used the same delimiter to split the string.

Demonstration video