Question

I want to define a function which can mutate the inputted list by adding 1's([1,1,1,...]) in to it. But, I don't want to use loops to perform this simple operation.

# input - a list (empty list)
#       - number of elements to initialize
# output- None
#       - But it will have to mutate the inputted (list)
def initialize_one(empty_lis, n):
    # Do nothing if e_lis is a non-empty list
    if len(empty_lis) is not 0:
        return
    else:
        temp = [1] * n
        # empty_lis = temp will not mutate
        # And I don't want to use loops to append
        # because if n = 100,000
        # it will have to loop for 100,000 times


lis = []
n = 10
initialize_one(lis, n)

print lis
# expected output
# >>>[1, 1, 1, 1, 1, 1, 1, 1, 1]
Was it helpful?

Solution

def initialize_one(seq, n):
    if not seq:
        seq[:] = [1] * n
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top