Home > Net >  can't append string to a list
can't append string to a list

Time:01-13

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

CodePudding user response:

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".

  • Related