Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List slicing issue
#1
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()
Reply
#2
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]).
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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()
Reply
#4
(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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  List Comprehension Issue johnywhy 5 438 Jan-14-2024, 07:58 AM
Last Post: Pedroski55
  Python List Issue Aggie64 5 1,563 Jun-30-2022, 09:15 PM
Last Post: Aggie64
  List to table issue robdineen 2 1,435 Nov-07-2021, 09:31 PM
Last Post: robdineen
  Calculator code issue using list kirt6405 4 2,202 Jun-11-2021, 10:13 PM
Last Post: topfox
  slicing and indexing a list example leodavinci1990 4 2,286 Oct-12-2020, 06:39 AM
Last Post: bowlofred
  Issue accessing data from Dictionary/List in the right format LuisSatch 2 2,169 Jul-25-2020, 06:12 AM
Last Post: LuisSatch
  For List Loop Issue Galdain 2 2,017 Dec-31-2019, 04:53 AM
Last Post: Galdain
  Help with slicing a list FWendeburg 3 2,548 Dec-02-2019, 04:57 PM
Last Post: michael1789
  IndexError: List index out of range issue Adem 1 3,476 Nov-01-2019, 10:47 PM
Last Post: ichabod801
  List/String seperation issue YoungGrassHopper 13 5,353 Sep-20-2019, 11:57 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020