Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to sort a list in a "for in"-loop (Python)

So I have this:

Channel.groups.sort() # Channel.groups is a list of strings

for country in Channel.groups:
    print(country)

But I would like to do something like this:

for country in Channel.groups.sort():
        print(country)

# This results in error: TypeError: 'NoneType' object is not iterable

Is it possible to somehow force Channel.groups.sort() to "execute" before it starts to iterate through the list?

like image 898
Fredrik Avatar asked Nov 29 '25 11:11

Fredrik


1 Answers

sort() is inplace, meaning it modifies the original list it is called upon and returns None (which is why you are getting the error 'NoneType' object is not iterable).

You will need to use something that leaves the original list intact and returns a new, sorted list, like sorted():

for country in sorted(Channel.groups)

like image 58
DeepSpace Avatar answered Dec 02 '25 02:12

DeepSpace



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!