Skip to content Skip to sidebar Skip to footer

Pythonic Conversion To Singleton Iterable If Not Already An Iterable

Suppose I have def distance2(vector1, vector2): zipped = zip(vector1, vector2) difference2 = [(vector2 - vector1) ** 2 for (vector1, vector2) in zipped] return sum(diff

Solution 1:

You are describing the basic usage of always_iterable.

>>>from more_itertools.more import always_iterable>>>for val in always_iterable(1):...print(val)...
1

Solution 2:

You can use numpy:

np.atleast_1d(1)
# array([1])

np.atleast_1d([1,2,3])
# array([1,2,3])

Post a Comment for "Pythonic Conversion To Singleton Iterable If Not Already An Iterable"