mixing set and list operations

Carl Meyer carl at oddbird.net
Thu Apr 30 12:16:42 EDT 2015


Hi Tim,

On 04/30/2015 10:07 AM, Tim wrote:
> I noticed this today, using Python2.7 or 3.4, and wondered if it is implementation dependent:
> 
> You can use 'extend' to add set elements to a list and use 'update' to add list elements to a set.
> 
>>>> m = ['one', 'two']
>>>> p = set(['three', 'four'])
>>>> m.extend(p)
>>>> m
> ['one', 'two', 'four', 'three']
> 
>>>> m = ['one', 'two']
>>>> p = set(['three', 'four'])
>>>> p.update(m)
>>>> p
> set(['four', 'three', 'two', 'one'])
> 
> 
> Useful if you don't care about ordering. Not sure if it's dangerous.

I don't think this is surprising, nor implementation dependent, nor
dangerous. Lists have an `extend()` method, sets have an `update()`
method. Both of these methods take any iterable as input, they don't
needlessly constrain the input to be of the same type as the base
object. That's the Pythonic way to do it; I'd be surprised if it didn't
work.

Carl

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20150430/4c4a508a/attachment.sig>


More information about the Python-list mailing list