Python: My for loop doesn't iterate over all items in a list

While following an online course about Python, we were encouraged to write a certain program ourselves. This was not for a mark, but only for practice. I don't want help solving the problem, but I need help as to why my code isn't doing what I thought it would be doing.

The (relevant) part of code is the following:

raw_restaurants = file.readlines()

print(raw_restaurants)

restaurants = []
information = []
for i in raw_restaurants:
    if len(information) < 5:
        information.append(i.strip())
    if len(information) ==  5:
        restaurants.append(information)
        information = []

And this is the list used. The original list is one created with file.readlines().

['Georgie Porgie\n', '87%\n', '$$$\n', 'Canadian,Pub Food\n', '\n',
 'Queen St. Cafe\n', '82%\n', '$\n', 'Malaysian,Thai\n', '\n',
 'Dumplings R Us\n', '71%\n', '$\n', 'Chinese\n', '\n',
 'Mexican Grill\n', '85%\n', '$$\n', 'Mexican\n', '\n',
 'Deep Fried Everything\n', '52%\n', '$\n', 'Pub Food\n']

The problem is that my function gives as output:

[['Georgie Porgie', '87%', '$$$', 'Canadian,Pub Food', ''],
 ['Queen St. Cafe', '82%', '$', 'Malaysian,Thai', ''],
 ['Dumplings R Us', '71%', '$', 'Chinese', ''],
 ['Mexican Grill', '85%', '$$', 'Mexican', '']]

Which means that the whole part about Deep Fried Everything has disseapeared.
Anyone knows what I am doing wrong?

You only have 4 items past the empty line of the Mexican Grill entry, so the if len(information) == 5: test never becomes True.

Simply append information one more time if there are items in it:

for i in raw_restaurants:
    if len(information) < 5:
        information.append(i.strip())
    if len(information) ==  5:
        restaurants.append(information)
        information = []
if information:
    restaurants.append(information)

Related Articles
You Might Also Like