can't append string to a list

Question:

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

Asked By: sha

||

Answers:

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

Answered By: Matt Pitkin
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.