Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good coding style: use temporary variable for list length or not? [closed]

Tags:

python

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?

like image 300
Graf Avatar asked Dec 19 '13 20:12

Graf


1 Answers

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.

like image 79
Marcin Avatar answered Sep 20 '22 06:09

Marcin