When I import a data set into an array, the length of each element appears as 1

133 Views Asked by At

I'm making a program where I import a long list of words from a .txt file into one array called wordlist. I then want to sort them into categories based on the length of the words. However for some reason, when the words are stored in the array, the length shows up as 1 for every single one.

Here is the code

wordlist = []
with open('words.txt', 'r') as words:
    for line in words:
        strplines = line.strip()
        list = strplines.split()
        wordlist.append(list)
        loading = loading + 1
        print(loading,'/ 113809 words loaded')

If I then do something like this

print(len(wordlist[15000]))

The output is 1 despite that word actually being 6 characters long. I tried this in another program, but the only difference was that I manually inputted a few elements into the array and it worked. That means theres probably an issue with the way I strip the lines from the .txt file.

2

There are 2 best solutions below

0
saint_burrito On BEST ANSWER

So the wordlist is an array of arrays? If so when you check the len of it's element, it would return the number of elements in this array so 1. But if you do something like

len(wordlist[1500][0])

you get the len of the first word that is stored in array at index 1500.

0
Serge Ballesta On

It looks that you do not want to append to the array (you would add a list), but you want to extend the array.

And please, please, even if builtins are not reserved words, avoid to use them! So call your list lst or mylist or whatever but not list...

The code could become:

wordlist = []
with open('words.txt', 'r') as words:
    for line in words:
        strplines = line.strip()
        lst = strplines.split()
        wordlist.extend(lst)
        loading = loading + 1
        print(loading,'/ 113809 words loaded')