2

I am reading two columns of values out of a .csv file a line at a time, which yields a list of row entries made up of two strings (something like ['cat1', 'dog1'])

When I iterate over all the rows I extracted I try to put all the "cats" in one list and "dogs" in another, kind of like this:

for row in csv_file_entries:
    catlist.extend(row[0])
    doglist.extend(row[1])

I expect doglist to be:

['dog1', 'dog2', 'dog3', 'dog4', ..., dogN]

but instead I get

['d', 'o', 'g', '1', ' ', 'c', 'a', 't', '1', ' ', ...] ETC

I suspect when I find out why the characters are the list elements instead of the strings I will also figure out why the cats and dogs are in the same list, even though the row elements 0 are dogs and row elements 1 are cats.

My actual code, with silly debug statements is below:

# get csv file containing digitized EOT data
# first column is day of year, second is EOT minutes
# taken from US Naval Obs site and digitized with web digitizer program
fname = 'C:\\time_calculator\\EOT.csv'
dtzd_DOY = dtzd_EOT = []
print("tarrtart", dtzd_DOY)
with open(fname, 'rt') as csvfile:
    eot_entries = csv.reader(csvfile, delimiter=',')
#    print(eot_entries)
    print("pooooty", dtzd_DOY, dtzd_EOT)
    for row in eot_entries:
        print(row, row[0], row[1])
        thisDOY = row[0]
        thisEOT = row[1]
        print(thisDOY)
        print(thisEOT)
#        thisEOT = "heychittyfgfgfttrgrtfgrt"
        dtzd_DOY.extend(thisDOY)
        dtzd_EOT.extend(thisEOT)
print(dtzd_DOY, dtzd_EOT)

This is my first question, so don't feel bad about correcting my form.

Andy Kellett
  • 41
  • 1
  • 5
  • 2
    `.extend()` adds each item in a sequence. A string is a sequence of characters. If you want to add it as one item, use `.append()`. – zondo Apr 20 '17 at 23:14
  • Yes - I thought I had checked .append versus .extend, but apparently not. Also, found that my initialization of my two lists A = B = [] was what was causing my mixing of entries. All is fixed. Thanks everyone. – Andy Kellett Apr 21 '17 at 16:15

1 Answers1

4

list.extend extends the list with each of the items in the iterable you pass. A string is an iterable of characters, so it appends the characters.

Easier to use list.append here.

kindall
  • 178,883
  • 35
  • 278
  • 309