mixing set and list operations

Ben Finney ben+python at benfinney.id.au
Thu Apr 30 19:04:30 CEST 2015


Tim <jtim.arnold at gmail.com> writes:

> You can use 'extend' to add set elements to a list and use 'update' to
> add list elements to a set.

And you can use both of those methods to add items from a file::

    >>> foo = ['one', 'two']
    >>> bar = open('/usr/share/common-licenses/GPL-3')
    >>> foo.extend(bar)
    >>> foo
    ['one', 'two', '                    GNU GENERAL PUBLIC LICENSE\n',
     ' Version 3, 29 June 2007\n', '\n',
     …

You have merely discovered that ‘list.extend’ and ‘set.update’ accept an
iterable <URL:https://wiki.python.org/moin/Iterator>.

Sets and lists and files and many other collections are all iterables,
so any of them can be passed to a function that accepts an iterable.

-- 
 \          “It's dangerous to be right when the government is wrong.” |
  `\                                   —Francois Marie Arouet Voltaire |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list