[Chicago] Deleting from a list or dictionary while processing it

Jason Wirth wirth.jason at gmail.com
Sat Mar 25 19:43:05 EDT 2017


Deque has a pop left.

On Sat, Mar 25, 2017, 6:35 PM Aaron Elmquist <elmq0022 at umn.edu> wrote:

> Hey Douglas,
>
> I hope you see the advantage of Jordan's solution.
>
> If you copy the list over again and again like your example the runtime is
> O(n^2) .
>
> Popping from the end of the list, list like Jordan, is a constant time
> operation.  Processing the whole list is then O(n) which scales​ better.
>
> Here's a good reference for you:
>
> https://wiki.python.org/moin/TimeComplexity
>
> Aaron
>
> On Mar 25, 2017 5:16 PM, "Jordan Bettis" <jordanb at hafd.org> wrote:
>
> If you're trying to use a list as a stack you can just use list.pop:
>
> In [1]: my_stack = [1,2,3,4,5,6]
>
> In [2]: while len(my_stack) > 0:
>    ...:     print(l.pop())
>    ...:
> 6
> 5
> 4
> 3
> 2
> 1
>
>
> On 03/25/2017 04:59 PM, Lewit, Douglas wrote:
>
> Hi guys,
>
> I remember doing some of this once upon a time, but I may have forgotten
> the details, so if someone could refresh my memory that would be great.
>
> In essence, what I'm trying to do is process a list ( or perhaps a
> dictionary ) BUT WHILE I'M PROCESSING IT I WANT TO MUTATE IT BY DELETING
> ELEMENTS FROM IT.  Does that make sense?
>
> ( Launching Python interpreter to provide a concrete example! )
>
> *while** my_list:*
>
>       *for** n **in** my_list[:]:*
>
> *            print**(n)*
>
>             *my_list = my_list[**1**:]*
>
>
> I think that's correct.... but still.... it can get a bit confusing.
> Okay, thanks for the feedback.
>
>
> Best,
>
>
> Douglas.
>
>
>
>
> _______________________________________________
> Chicago mailing listChicago at python.orghttps://mail.python.org/mailman/listinfo/chicago
>
>
>
> _______________________________________________
> Chicago mailing list
> Chicago at python.org
> https://mail.python.org/mailman/listinfo/chicago
>
>
> _______________________________________________
> Chicago mailing list
> Chicago at python.org
> https://mail.python.org/mailman/listinfo/chicago
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20170325/90efdb22/attachment.html>


More information about the Chicago mailing list