Wednesday, January 23, 2019

So a list and a tuple walk into a sum()

As a direct side effect of glom's 19.1.0 release, the authors here at PDW got to re-experience one of the more surprising behaviors of three of Python's most basic constructs:
Most experienced developers know the quickest way to combine a short list of short lists:
list_of_lists = [[1], [2], [3, 4]]
sum(list_of_lists, [])
# [1, 2, 3, 4]
Ah, nice and flat, much better.

But what happens when we throw a tuple into the mix:
list_of_seqs = [[1], [2], (3, 4)]
sum(list_of_seqs, [])
# TypeError: can only concatenate list (not "tuple") to list
This is kind of surprising! Especially when you consider this:
seq = [1, 2]
seq += (3, 4)
# [1, 2, 3, 4]
Why should sum() fail when addition succeeds?! We'll get to that.
new_list = [1, 2] + (3, 4)
# TypeError: can only concatenate list (not "tuple") to list
There's that error again!

The trick here is that Python has two addition operators. The simple "+" or "add" operator, used by sum(), and the more nuanced "+=" or "iadd" operator, add's inplace variant.

But why is ok for one addition to error and the other to succeed?

Symmetry. And maybe commutativity if you remember that math class.

"+" in Python is symmetric: A + B and B + A should always yield the same result. To do otherwise would be more surprising than any of the surprises above. list and tuple cannot be added with this operator because in a mixed-type situation, the return type would change based on ordering.

Meanwhile, "+=" is asymmetric. The left side of the statement determines the type of the return completely. A += B keeps A's type. A straightforward, Pythonic reason if there ever was one.

Going back to the start of our story, by building on operator.iadd, glom's new flatten() function avoids sum()'s error-raising behavior and works wonders on all manner of nesting iterable.

55 comments:

  1. Wow, this is new to me. Thanks for sharing it.

    ReplyDelete
  2. "+" is not very symmetric when you're adding strings... (or lists, for that matter, [1] + [2] != [2] + [1]).

    ReplyDelete
  3. >>> a=[4,6]
    >>> a += (i**2 for i in range(4))
    >>> a
    [4, 6, 0, 1, 4, 9]

    ReplyDelete
  4. Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. satta king

    ReplyDelete
  5. A round of applause for your article.Much thanks again. Really Cool. Satta king

    ReplyDelete
  6. Might as well look at itertools.chain

    ReplyDelete
  7. Such a very useful article. Very interesting to read this article. I would like to thank you for the efforts you had made for writing this awesome article.
    Data Science Course in Pune
    Data Science Training in Pune

    ReplyDelete
  8. All of these posts were incredible perfect. It would be great if you’ll post more updates.
    Data Science Course in Bangalore

    ReplyDelete
  9. These thoughts just blew my mind. I am glad you have posted this.
    Data Science Training in Bangalore

    ReplyDelete
  10. I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.
    Data Science Institute in Bangalore

    ReplyDelete
  11. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.
    Data Science Certification in Bangalore

    ReplyDelete
  12. Very awesome!!! When I seek for this I found this website at the top of all blogs in search engine. Oregon Business Registry

    ReplyDelete
  13. I have been searching to find a comfort or effective procedure to complete this process and I think this is the most suitable way to do it effectively. Oregon Business Registry

    ReplyDelete
  14. This is an excellent post I seen thanks to share it. It is really what I wanted to see hope in future you will continue for sharing such a excellent post.
    토토사이트

    ReplyDelete
  15. This is really very nice post you shared, i like the post, thanks for sharing.. 먹튀검증

    ReplyDelete
  16. I have a mission that I’m just now working on, and I have been at the look out for such information. 토토사이트

    ReplyDelete
  17. Suppose if someone has bet 10 rupees on a number, then if that number is opened then the user will get 10 x 90 = 900 Rupees. Similarly, users will get 1800 rupees for 20 rupees, 2700 rupees for 30 rupees, 3600 rupees for 40 rupees and 4500 rupees for 50 rupees. The user can invest as much money as he wants on one number and can play many numbers as he wants. satta 786

    ReplyDelete
  18. Super site! I am Loving it!! Will return once more, I’m taking your food additionally, Thanks. 먹튀사이트

    ReplyDelete
  19. From one day, I noticed that many people post a lot of articles related to 안전놀이터. Among them, I think your article is the best among them!!I

    ReplyDelete
  20. What an interesting story! I'm glad I finally found what I was looking for Excellent reading 안전놀이터, I read a lot of posts but I am really impressed with your post. Thanks sir, I will look into this article. To know about me, try talking to 사설토토사이트.

    ReplyDelete
  21. Hello
    Thank you for giving me useful information.
    Please keep posting good information in the future
    I will visit you often. Thank you.
    I am also running the site. 안전놀이터 This is a related site, so please visit once.
    Have a niceday!

    ReplyDelete
  22. You can comment on the blog ordering system. You should discuss, it's splendid. Auditing your blog would increase the number of visitors. I was very happy to find this site. Thank you...

    Data Science Certification in Bangalore

    ReplyDelete
  23. I am overwhelmed by your post with such a beautiful subject. I usually visit their blogs and update myself through the information they contain, but today's blog would be most appreciated. Well done!
    Data Science Training in Pune

    ReplyDelete
  24. I saw your article well. You seem to enjoy 바카라사이트 for some reason. We can help you enjoy more fun. Welcome anytime :-)

    ReplyDelete
  25. I am sure it will help many people. Keep up the good work. It's very compelling and I enjoyed browsing the entire blog.
    Data Science In Bangalore

    ReplyDelete
  26. From this post I know that your good knowledge of the game with all the pieces has been very helpful. I inform you that this is the first place where I find problems that I look for. You have a clever but attractive way of writing.
    Data Analytics Courses in Bangalore

    ReplyDelete
  27. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work. 토토사이트

    ReplyDelete
  28. Hello, I am one of the most impressed people in your article. 토토커뮤니티 I'm very curious about how you write such a good article. Are you an expert on this subject? I think so. Thank you again for allowing me to read these posts, and have a nice day today. Thank you.

    ReplyDelete
  29. First of all, thank you for letting me see this information. I think this article can give me a lot of inspiration. I would appreciate 카지노사이트 if you could post more good contents in the future.

    ReplyDelete
  30. I am overwhelmed by your post with such a nice topic. Usually I visit your 안전놀이터 and get updated through the information you include but today’s blog would be the most appreciable. Well done!

    ReplyDelete
  31. One other issue is when you are in a predicament where you would not have a co-signer then you may genuinely wish to try to exhaust all of your financing options. You can get many grants or loans and other grants휴게텔

    that will give you finances to assist with school expenses. Thank you for the post.

    ReplyDelete
  32. I've been searching for hours on this topic and finally found your post. , I have read your post and I am very impressed. We prefer your opinion and will visit this site frequently to refer to your opinion. When would you like to visit my site? 토토커뮤니티

    ReplyDelete
  33. I'm writing on this topic these days, , but I have stopped writing because there is no reference material. Then I accidentally found your article. I can refer to a variety of materials, so I think the work I was preparing will work! Thank you for your efforts. 토토사이트

    ReplyDelete
  34. Easily, the article is actually the best topic on this registry related issue. I fit in with your 먹튀검증 and will eagerly look forward to your next updates. Just saying thanks will not just be sufficient, for the fantastic lucidity in your writing. I will instantly grab your rss feed to stay informed of any updates

    ReplyDelete
  35. Yes i am totally agreed with this article and i just want say that this article is very nice and very informative article.I will make sure to be reading your blog more. You made a good point but I can't help but wonder for 안전놀이터, what about the other side? !!!!!!Thanks

    ReplyDelete
  36. Thank you so much for providing good quality information. I think it would not have been easy to collect this information and organize it in an easy to understand way. I'll add it to my bookmarks so I can visit it often! And I will share it with my acquaintances. And there is a lot of useful information on our website too, so please take a look and take a look. Then have a good day. 먹튀검증

    ReplyDelete
  37. Hi ! I specialize in writing on these topics. My blog also has these types of articles and forums. Please visit once. 메이저놀이터

    ReplyDelete
  38. I was surfing net and fortunately came across this site and found very interesting stuff here. Its really fun to read. I enjoyed a lot. 토토사이트 Thanks for sharing this wonderful information.

    ReplyDelete
  39. Looking at this article, I miss the time when I didn't wear a mask. 온라인바둑이 Hopefully this corona will end soon. My blog is a blog that mainly posts pictures of daily life before Corona and landscapes at that time. If you want to remember that time again, please visit us.

    ReplyDelete
  40. That's a really impressive new idea! It touched me a lot. 토토사이트 I would love to hear your opinion on my site. Please come to the site I run once and leave a comment. Thank you.

    ReplyDelete
  41. Of course, your article is good enough, 먹튀검증 but I thought it would be much better to see professional photos and videos together. There are articles and photos on these topics on my homepage, so please visit and share your opinions.

    ReplyDelete
  42. Happy to chat on your blog, I feel like I can't wait to read more reliable posts and think we all want to thank many blog posts to share with us.

    Business Analytics Course

    ReplyDelete
  43. Really impressed! Everything is a very open and very clear clarification of the issues. It contains true facts. Your website is very valuable. Thanks for sharing.
    Best Data Science Courses in Bangalore

    ReplyDelete
  44. It's always a pleasure to read your magnificent articles on this site. You are among the top writers of this generation, and there's nothing you can do that will change my opinion on that. My friends will soon realize how good you are. 온라인포커

    ReplyDelete
  45. t's always a pleasure to read your magnificent articles on this site. You are among the top writers of this generation 토토

    ReplyDelete
  46. my Instagram followers and I’m sure they’ll enjoy it as well. It’s an amazing lighting idea. 먹튀검증사이트

    ReplyDelete
  47. I blog quite often and I genuinely appreciate your information. 스포츠사이트

    ReplyDelete
  48. Howdy! This blog post couldn't be written much better! Going through this article reminds me of my previous roommate! 안전놀이터

    ReplyDelete
  49. Instagram followers and I’m sure they’ll enjoy it as well 먹튀검증

    ReplyDelete
  50. From this post I know that your good knowledge of the game with all the pieces has been very helpful. I inform you that this is the first place where I find problems that I look for. You have a clever but attractive way of writing.

    Data Analytics Course in Bangalore

    ReplyDelete
  51. Woohoo! It is an amazing and useful article. I really like. It's so good and so amazing. I am amazed. I hope you will continue to do your job in this way in the future as well.

    Digital Marketing Course in Bangalore

    ReplyDelete