Hackerss.com

hackerss
hackerss

Posted on

Insert a new item before the second element in an existing array in Python

Insert a new item before the second element in an existing array - Python:


def insert_num(num_list, new_num):
    """
    Insert a new item before the second element in an existing array.

    Parameters
    ----------
    num_list : list
        The list of numbers.
    new_num : int
        The new number to insert.

    Returns
    -------
    list
        The list of numbers with the new number inserted.
    """

    #insert the new number before the second element in the list
    num_list.insert(1, new_num)

    #return the list of numbers with the new number inserted
    return num_list

#example
result = insert_num([1, 2, 3, 4], 99)
#output
print(result)  #[1, 99, 2, 3, 4]


Enter fullscreen mode Exit fullscreen mode

Top comments (0)