Python Forum

Full Version: List slicing issue
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So I have a problem that I've been working on for like 8 hours now. It's driving me insane.

The goal here is to open a .txt file I created that contains a list of names that go from top to bottom.
Then I want the program to look at the first letter of each name and see if it is the same as the first letter of the following name.
If the name does not contain the same letter, the program is to use a \n to go to a new line. That way all the first letters are grouped together.

def main():

    newList = []
    
    #Opens the file.
    inFile = open("names.txt", 'r')

    #Reads all of the lines and saves them to inRead.
    inRead = inFile.readlines()

    #Sorts them alphabetically.
    inRead.sort()

    #Performs a loop for how many items are in 'inRead'.
    for index in range(len(inRead)):

        #Strips off all the new lines.
        inRead[index] = inRead[index].rstrip('\n')

        #Creats a list called newList.
        newList = inRead[index]

        #If the first letter of one name is not the same as the first
        # letter of the next name then skip a line.
        if newList[0][0] != newList[0][1]:

            print('\n')

        print(newList)
        
    #Closes the file.
    inFile.close()

main()
First, don't iterate over indexes, iterate over list items themselves. Let's redo your code with that, and it will illuminate your problem.

def main():
 
    newList = []
     
    # Get the sorted file lines.
    inFile = open("names.txt", 'r')
    inRead = inFile.readlines()
    inRead.sort()
 
    #Performs a loop for how many items are in 'inRead'.
    for name in inRead:
        name = name.rstrip('\n')
 
        #Creats a list called newList.
        newList = name
 
        #If the first letter of one name is not the same as the first
        # letter of the next name then skip a line.
        if newList[0][0] != newList[0][1]:
            print('\n')
        print(newList)
         
    #Closes the file.
    inFile.close()

main()
Hopefully you can now see that you are resetting newList to the current name each time through the loop. You are not storing names so that you can compare them. You should instead append each name to newList. Then you can compare the last item in newList (newList[-1]) to the previously last item in newList (newList[-2]).
I am now even more confused. Now I'm getting new errors.

Error:
Traceback (most recent call last): File "C:\Users\Irhcsa\Desktop\test.py", line 26, in <module> main() File "C:\Users\Irhcsa\Desktop\test.py", line 19, in main if newList[0][0] != newList[0][1]: IndexError: string index out of range
When I try to run your code. I think I might be mentally retarded or something.

When I append the items how do I get rid of the blank spaces that show ''?

def main():
  
    newList = []
      
    inFile = open("names.txt", 'r')
    inRead = inFile.readlines()
    inRead.sort()
  
    for name in inRead:
        name = name.rstrip('\n')

        newList.append(name)

    print(newList)
    inFile.close()
 
main()
(Apr-26-2019, 07:33 PM)Irhcsa Wrote: [ -> ]When I append the items how do I get rid of the blank spaces that show ''?
Check that it's not empty:
for line in inRead:
    name = name.strip()
    if name:
        newList.append(name)