This question is related to python, but it is actually common for many languages. Take a look at that code:
import sys
people = ['John', 'Jack', 'Charles']
cities = ['London', 'Liverpool', 'Manchester']
if (len(cities) != len(people)):
print "Error! Length of cities list \
(%s) differs from length of people list (%s)" % (len(cities), len(people))
sys.exit(1)
for i in xrange (len(cities)):
print "Hello, %s from %s" %(people[i], cities[i])
Seems correct. But at this small fragment len is called 3 to 5 times (3 times if lists' lengths are equal, 5 times if lists' lengths differ). Do we need to rewrite code like this?
import sys
people = ['John', 'Jack', 'Charles']
cities = ['London', 'Liverpool', 'Manchester']
people_count = len(people)
cities_count = len(cities)
if (cities_count != people_count):
print "Error! Length of cities list \
(%s) differs from length of people list (%s)" % (cities_count, people_count)
sys.exit(1)
for i in xrange (cities_count):
print "Hello, %s from %s" % (people[i], cities[i])
In the other words: in which cases do we need temporary variable for storing list length, and in which cases it is not needed?
I think that this falls within Do Not Repeat Yourself: if you wanted to change away from using that length, you'd have to change about five things, but if you used a variable, it would probably just be that one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With