Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is there a range error in the for loop?

def frequency_analysis(string):
    count = 0
    freq_list = [
        [[" "] * len(string)],
        []
        ]
    print(freq_list[0])
    for i in range(len(string)):
        print(i)
        freq_list[0][i] = string[i]
        print(freq_list[0])
    return freq_list
print(frequency_analysis("fhfhffffj"))
print(frequency_analysis("jfjf"))

This is for a school assignment and I am not allowed to use built in functions other than len(). I am trying to make the freq_list[0] a list of separate characters from the string input. For some reason, after the first switch it turns the first list created into a list of just one item and then there is an out of range error. Can anyone explain why this is happening.

Input "fhh"
prints:

[" "," "," "]
0
"f"
1
Error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

At freq_list[0], your are creating a nested list. You should either declare it with

freq_list = [
    [" "] * len(string),
    []
    ]

if the nesting is unwanted, or assign values in it with

freq_list[0][0][i] = string[i]

Here, with the two [0] indexing, you do access the inner list which you originally want to assign values within.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading