Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #102406
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Behaviour of list comprehensions |
| Date | 2016-02-02 15:08 +0100 |
| Organization | None |
| Message-ID | <mailman.15.1454422532.3032.python-list@python.org> (permalink) |
| References | <4a9ac629-98fa-4643-af28-8d30b52bbc50@googlegroups.com> |
arsh.py@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.
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Behaviour of list comprehensions arsh.py@gmail.com - 2016-02-02 05:30 -0800 Re: Behaviour of list comprehensions Steven D'Aprano <steve@pearwood.info> - 2016-02-03 00:58 +1100 Re: Behaviour of list comprehensions Peter Otten <__peter__@web.de> - 2016-02-02 15:08 +0100
csiph-web