[Tutor] Please look at my wordFrequency.py
Kent Johnson
kent37 at tds.net
Wed Oct 12 00:00:13 CEST 2005
Andrew P wrote:
> Just want to add a little something here, because reading over this
> thread, I think there may have been some confusion:
>
> Kent wrote:
>
> for e in saveRemovedForLaterL:
> L.append(e)
> could be
> L.extend(e)
>
> I think he might have meant:
>
> for e in saveRemovedForLaterL:
> L.append(e)
> could be
> L.extend(saveRemovedForLaterL)
Right you are, thanks for the catch!
Kent
>
> The difference between these is that one is explicitly looping with
> Python, accessing each element of the first list one at a time,
> appending it to the other one at a time. Whereas if you call extend()
> instead, it will be doing that looping for you with the extend() method,
> written in C, and very quickly indeed. I would worry less about what is
> written in C vs what is built-in, and does implicit looping for you.
> Any time you can avoid stepping over a list one element at a time, is
> usually the faster way.
>
> >>> lst = [1,2,3,4]
> >>> lst2 = [5,6,7,8]
> >>> lst.extend(lst2)
> >>> print lst
> [1, 2, 3, 4, 5, 6, 7, 8]
>
> Compare this to:
>
> >>> lst = [1,2,3,4]
> >>> lst2 = [5,6,7,8]
> >>> for num in lst2:
> ... lst.append(num)
> >>> print lst
> [1, 2, 3, 4, 5, 6, 7, 8]
>
>
> FWIW, append is generally used to generate a list from something
> calculated on the fly:
>
> >>> lst = []
> >>> for i in range(10):
> ... lst.append(i)
> ...
> >>> print lst
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>
>
>
> Ah. But how can I know what is in C code and what isn't? For example, in
> a previous post you say that L.extend(e) is in C, and imply that
> L.append(e) isn't, and that therefore L.extend(e) should be used.
>
> Well, back to Hetlands' Beginning Python.
>
> Dick
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list