[Python] Indexing in calling instructions. Would it be possible that a function could detect...

Discussão em 'Python' iniciado por Stack, Janeiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    Having a function that returns a list:

    def func1(list1):
    func1_result = list1 * 2 # This is just an illustrative example to simply show that the function returns a list resulting from any function calculation.
    return func1_result


    And getting the whole list returned by the function with:

    Example 1:

    list1_1 = [5, 4, 3, 2, 1]

    print(f"{func1(list1_1)}") # "[5, 4, 3, 2, 1, 5, 4, 3, 2, 1]"


    Or also getting the value of a specific index of the list returned by the function, with:

    Example 2:

    list1_1 = [5, 4, 3, 2, 1]

    print(f"{func1(list1_1)[0]}") # "5"


    Then, the question is about, is there any way where the function func1 could detect if the calling instruction syntax/format is including or not the indexing part [n]? and also, when including the indexing part [n], then, how to know what specific index value is in the function calling instruction?

    def func1(list1):
    func1_result = []

    '''
    if the function calling instruction is about getting the whole resulting list:
    do the function calculations to get the whole resulting list `func1_result`.
    elif the function calling instruction is about getting one specific index value of the resulting list:
    do the function calculations to get only the resulting value for the specified index.
    # In this case the result could be a 1-element list.
    # Main goal for this case: saving memory during calculations when working with large lists and with many function's calls.
    '''

    return func1_result


    My understanding is that the indexing access specified in the calling instruction takes place after the function returns the resulting list, but maybe there would be a kind of way (ideally a direct way) which the function could get this calling format information from the calling instruction, without the need to specify it manually with an additional function parameter.

    Continue reading...

Compartilhe esta Página