Identical or not?

Screen Link:

https://app.dataquest.io/m/356/guided-project%3A-exploring-hacker-news-posts/3/extracting-ask-hn-and-show-hn-posts

My Code:

1st code: 

ask_posts = []
show_posts = []
other_posts = []
for row in hn:
    title = row[1]
    title = title.lower() 
    if title.startswith("ask hn"):
        ask_posts.append(title)
    elif title.startswith("show hn"):
        show_posts.append(title)
    else:
        other_posts.append(title)
        
2nd code :

posts = []
for row in hn:
    title = row[1]
    if title.lower().startswith("ask hn"):
        posts.append(title)
        
print(len(ask_posts))
print(len(posts))
print(posts == ask_posts)

What I expected to happen:

I expected ask_posts and posts to be same, though the len function shows they have the same length but when i check if they are identical, it says false. it’s almost the same code except i used .lower() method inside the if statement in the 2nd code.

Replace this line with the output/error


<!--NO ERROR JUST EXPECTED POSTS AND ASK_POTS WOULD BE SAME--!>

You can print out a row from each of those and check the difference -

print(posts[1])
print(ask_posts[1])

The above results -

Ask HN: Am I the only one outraged by Twitter shutting down share counts?
ask hn: am i the only one outraged by twitter shutting down share counts?

As you can see ask_posts results in all lowercase letters. Because, in your code for ask_posts you have -

title = title.lower() 

But you don’t have that for when you create posts.

Do note that using title.lower() does not mean that title will change in-place. If you print out title it will still have the same uppercase letters.

You need to store the output of title.lower() back to title for the changes to be “permanent”. Similar to how you did in the ask_posts code.

1 Like

Hi @sakethsai32,

That is because when you do title.lower().startswith("ask hn") it does not save the lowercase titles in the title variable. However, in the first code, you are saving the title.lower() back to the title variable. To get posts == ask_posts to be True, you’ll have to change the 2nd code to title = row[1].lower()

1 Like