Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jason Roberts
5,486 PointsWhich is better code efficiency wise, listing Len as a function in between the string literals or using {} and .format?
attendees = ["Karen", "Billy", "John"] print("There are {} attendees currently".format(len(attendees)))
opposed to
attendees = ["Karen", "Billy", "John"] print("There are", len(attendees), "attendees currently"
shown in the instructional video.
I noticed that you are able to use {} within the string literal just like before and use .format(len(attendees))). I was wondering which was the more politically correct statement.
1 Answer
Chris Freeman
Treehouse Moderator 68,468 PointsGreat question! According to this StackOverflow answer, using the + is the fastest for few variables, but as you get more, the new f strings in 3.6+ is the fastest method overall.
In a head-to-head comparison, the concatenation + is much faster than the .format() method, until you approach an extreme number of variables (like 250!). The chart in the answer gives the results for the other formats.
Jason Roberts
5,486 PointsThank you! This was a great answer!
Chris Freeman
Treehouse Moderator 68,468 PointsYou're very welcome! Great questions like this also help me refine my learning as I research the answer!
Michael Cook
Full Stack JavaScript Techdegree Graduate 28,975 PointsMichael Cook
Full Stack JavaScript Techdegree Graduate 28,975 PointsIn Python, the rule is that the simpler way is the better way. I think that concept applies universally, though. In terms of what is most efficient from a computing point of view, I would guess that the fewer lines of code, the less work the CPU has to do. Someone with some computer science knowledge would be able to give a better answer on that front. But at any rate, if something can be done with less code, do it that way. But there is no "politically correct" way to my knowledge.