python中的变异列表

时间:2013-06-16 08:39:37

标签: python list mutation

我想定义一个函数,它可以通过向其添加1([1,1,1,...])来改变输入列表。 但是,我不想使用循环来执行这个简单的操作。

# 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]

1 个答案:

答案 0 :(得分:3)

def initialize_one(seq, n):
    if not seq:
        seq[:] = [1] * n