Question

Let's consider a list called 'my_list` whose contents are as follows:

['10', '100', '1,000', '10,000', 100,000']

I want to verify that my_list is a list of stringified integers, which are multiples of 10 and are sorted in ascending order, so here's what i do

int_list = [int(each_int.replace(',', '')) for each_int in my_list]

boolean = all([int_list[idx] == int_list[idx-1]*10 for idx in xrange(1, len(int_list))])

my question is will the len() be called for every iteration? what is better practice in such cases?

  1. assign the length to a variable and use that instead of the len() itself in the list comprehension
  2. it doesn't matter, len() is executed only once for all the iterations

if 2. , is it applicable to cases when say, I am iterating through the values/ keys of a dictionary of lists (or maybe just a dictionary)

ex: d_list = [set(value) for value in my_dict.values()]

Was it helpful?

Solution

You can do it as:

my_list = ['10', '100', '1,000', '10,000', '100,000']

int_list = [int(each_int.replace(',', '')) for each_int in my_list]

>>> print all(i*10==j for i,j in zip(int_list, int_list[1:]))
True

This will avoid any unnecessary repetitions of calculations and is also my faster since it is doing comparison by division. I have also replaced all([...]) with all(...) since all can handle generators and will save from having to create a temporary list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top