0

I have a list in python, which is from a text document that I split at new line characters. The end of data is indicated with # in the text document. I need to count each of element of the list and then split the strings in the list at tab characters, creating a two dimensional list.

I thought this was fairly simple, however, I'm not getting a result from my code. The strings in the list are not splitting at all, nevermind at \t.

with open('names.txt') as names:
    records = names.read().split('\n')
recordcount = 0
for item in records:
    if item != '#':
        recordcount += 1
        item = item.split('\t')
print (records)
print (recordcount)

Has this got something to do with tab characters being troublesome? Or can I not replace elements of a list in-place? Should I be creating a new list with my split records?

2 Answers 2

3

You're just reassigning a local variable. This doesn't affect the contents of the list. Try this:

for i, item in enumerate(records):
    if item != '#':
        recordcount += 1
        records[i] = item.split('\t')
Sign up to request clarification or add additional context in comments.

1 Comment

Ohh, yes of course, that was obvious actually. Thank you!
1

You can replace list items in-place, but item = item.split('\t') just re-assigns the local variable item. You can easily replace the list item by e.g. records[index] = item. You can get the right index by using the enumerate function.

Your code changed to do what you want:

with open('names.txt') as names:                                            
    records = names.read().split('\n')                                      
recordcount = 0                                                             
for index, item in enumerate(records):                                      
    if item != '#':                                                         
        recordcount += 1                                                    
        item = item.split('\t')                                             
        records[index] = item                                               
print (records)                                                             
print (recordcount)

1 Comment

Yes, thank you. I should have looked more closely at my work, such an obvious error. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.