timman
timman

Reputation: 489

Program creating a list within a list when reading contents of file

I have found a fix for the following problem, however I'd like to understand why my below code creates a list of strings within a list, i.e. has this list of strings as the only element in an outer list.

I have a .txt file which I'm reading in which consists of about 25 sentences. It is just one long paragraph and so I wanted to split it into sentences, delimited by a full stop. I initially used this code to perform this step:

file = open("love_life.txt", "r")

list_of_sentences = []
for line in file:
    new = line.split('.')
    list_of_sentences.append(new)
file.close()
print(list_of_sentences)

I expected that this would create a list of strings, with each string representing a sentence delimited by a full stop. But instead, although it indeed created a list of strings/sentences it did so enclosed within another list. So when I tried to iterate over the list, I was just iterating one time over the nested list. Like this output:

[["lifeguards save lives", "time is of the essence", "the wind blows where it wants"]]

Can anyone tell me why this is happening with this code?

Upvotes: 0

Views: 30

Answers (2)

Pratik Joshi
Pratik Joshi

Reputation: 439

You should use extend(), if you dont want to end up with a list of list.

    file = open("love_life.txt", "r")

    list_of_sentences = []
    for line in file:
        new = line.split('.')
        list_of_sentences.append(new)
    file.close()
    print(list_of_sentences)

Upvotes: 0

wjandrea
wjandrea

Reputation: 33107

It's because line.split('.') returns a list, and list_of_sentences.append(new) adds that list to list_of_sentences. Maybe you meant to use list_of_sentences.extend(new) instead? That would add each element of new to list_of_sentences.

Upvotes: 1

Related Questions