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]
def initialize_one(seq, n):
if not seq:
seq[:] = [1] * n
来源:https://stackoverflow.com/questions/17131536/mutating-list-in-python