[Python] Pythonic conversion to singleton iterable if not already an iterable

Discussão em 'Python' iniciado por Stack, Maio 26, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose I have

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


    where distance2(vector1, vector2) finds the (squared) Euclidian distance between vector1 and vector2. The function will work for iterable elements, but suppose we also want to make it work for non-iterable elements (i.e. distance2(1,3)). Is there a pythonic way to do this? (i.e, automatically turning regular input into a singleton list).

    Continue reading...

Compartilhe esta Página