简体   繁体   中英

can't append string to a list

new_list = []

def calculatePermutations(sentence):
    permute = permutations(sentence)
    for i in permute:
        permutelist = i
        for j in permutelist:
            for z in range(len(i)):
                new_list.append("apple")
                print("it is printing")

print(new_list[0])


if __name__ == '__main__':
    sentence = keywords
    calculatePermutations(sentence)

I am trying to append some data from the function into the new_list but when i try to get that data from the list i am getting error:

IndexError: list index out of range

Alter your function, so that you define new_list within it and then return new_list at the end:

from itertools import permutations

def calculatePermutations(sentence):
    new_list = []
    permute = permutations(sentence)
    for i in permute:
        permutelist = i
        for j in permutelist:
            for z in range(len(i)):
                new_list.append("apple")
    return new_list

# call the function
mylist = calulatePermutations("Blah")

print(mylist[0])  # output should be apple

Note that in this case mylist will contain 384 instances of the string "apple" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM