0

I am trying to clean text file from '// type comentaries' that go from place they start to end of line in text. Using 3 lists:

row=[]
redakbezkom=[]
cleantext=[]

I need 'clean' text in form of list that consists of words used in text. Iterating through text results in good cleanup but append is saving multiple instances of lines in clean list.

 for line in Ulaz:
  niz = line
  del row[:]
  del redakbezkom[:]
  row=niz.split()
  for words in row:
    if words=='//':
      break
    else:
      redakbezkom.append(words)
  print redakbezkom
  cleantext.append(redakbezkom)
 print cleantext

Therefore print of cleantext results in: [ [last line] , ... (times number of line in text) ] instead of: [ [first line], [second line],...,[last line] ]

Why is append overwriting all former lines in list?

RubyHora
  • 19
  • 4

1 Answers1

0

del redakbezkom[:] clear the elements in the object, not created a new one. That's redakbezkom is always the same object for each line.

cleantext.append(redakbezkom) appended a reference to the object redakbezkom of each line. Then you got number of lines of the object redakbezkom.

Read this: How do I pass a variable by reference?

 for line in Ulaz:
  niz = line
  redakbezkom = []
  row=niz.split()
  for words in row:
    if words=='//':
      break
    else:
      redakbezkom.append(words)
  print redakbezkom
  cleantext.append(redakbezkom)

I fixed your code above, by create a new redakbezkom for each line. As row=niz.split() created a new list for row, so clear row isn't needed here.

Community
  • 1
  • 1
Binux
  • 697
  • 6
  • 12