Behaviour of list comprehensions

Peter Otten __peter__ at web.de
Tue Feb 2 09:08:19 EST 2016


arsh.py at gmail.com wrote:

> I am having some understandable behaviour from one of my function name
> week_graph_data() which call two functions those return a big tuple of
> tuples, But in function week_graph_data() line no. 30 does not
> work(returns no result in graph or error).
> 
> I have check both functions are called in week_graph_data() individually
> and those run perfectly. (returning tuple of tuples)
> 
> here is my code: pastebin.com/ck1uNu0U

> def week_list_func():
>     """ A function returning list of last 6 days in 3-tuple"""
>    
>     date_list = []
>     for i in xrange(7):
>         d=date.today() - timedelta(i)
>         t = d.year, d.month, d.day
>         date_list.append(t)
>     return reversed(date_list)

reversed(date_list) returns an "iterator":

>>> items = reversed(["a", "b", "c"])
>>> items
<list_reverseiterator object at 0x7f43622e9a20>

This means that iteration will "consume" the items

>>> list(items)
['c', 'b', 'a']
>>> list(items)
[]

and thus work only once. To allow for multiple iterations you can return a 
list instead:

>>> items = ["a", "b", "c"]
>>> items.reverse()
>>> items
['c', 'b', 'a']
>>> list(items)
['c', 'b', 'a']
>>> list(items)
['c', 'b', 'a']

Note that list.reverse() is a mutating method and by convention returns 
None. Therefore

   return date_list.reverse() # wrong!

will not work, you need two lines

   date_list.reverse()
   return date_list

in your code.



More information about the Python-list mailing list