Python – How to iterate over a variable that can be both an integer and an array?

How to iterate over a variable that can be both an integer and an array?… here is a solution to the problem.

How to iterate over a variable that can be both an integer and an array?

I want to make a multipurpose function that accepts both integers and integer arrays, like some numpy functions, eg delete do:

def foo(bar):   # type(foo) can be integer or an array of integers
    for i in bar:
        print(bar)

The problem is that when bar is a single int, this obviously throws a TypeError: 'int' object is not iterable. And I can’t find how to convert bar to an array or anything iterable and not break the code when bar is an array. What to do about this?

Solution

numpy.array has an optional ndmin parameter. Set it to 1 to guarantee that you are iterating over a one-dimensional array:

def foo(bar):   # type(bar) can be integer or an array of integers
    for i in np.array(bar, ndmin=1):
        print(i)

You can also specify copy=False to avoid making a copy when the input is already an array.

Note that I also modified your logic: you want to print i instead of bar when iterating.

Related Problems and Solutions