Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python converting set to list strange list behavior

Tags:

python

I must be missing something because this is strange...

a = ['a', 'b', 'c']
a1 = ['b', 'a']
foo = list( set(a) - set(a1))

** returning **

foo == ['c']
type(foo) == <type 'list'>
foo[0] == 'c'

** now the strange part **

foo = foo.insert(0, 'z')
foo == None

why do list operations like insert, and append cause foo to be None??

the following accomplishes what my top example attempts to but seems ridiculous.

import itertools

a = ['a', 'b', 'c']
a1 = ['b', 'a']

foo = list(set(a) - set(a1))
q = [['z']]
q.append(foo)
q = [i for i in itertools.chain.from_iterable(q)]
q == ['z', 'c']

any insight would be appreciated. thank you.

like image 711
Ryder Brooks Avatar asked Mar 26 '26 17:03

Ryder Brooks


1 Answers

foo.insert() returns None, but does change foo in the way you'd expect:

>>> foo = ['c']
>>> foo.insert(0, 'z')
>>> foo
['z', 'c']

If you wish to assign the result to a different variable, here is one way to do it:

>>> foo = ['c']
>>> bar = ['z'] + foo
>>> bar
['z', 'c']
like image 66
NPE Avatar answered Apr 02 '26 22:04

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!