[Tutor] Question about about PEP8

Alan Gauld alan.gauld at yahoo.co.uk
Tue Jul 7 04:12:06 EDT 2020


On 07/07/2020 07:45, Manprit Singh wrote:

> As i have read in PEP 8 , it suggests not to compare values to true or
> false using "==".  Secondarily it is also written in python documentation
> that empty collections and sequences (list, tuple set and dict) are
> considered false .

That is correct

> So I just need to know if the code written by me in two cases is correct or
> not:

But note hat PEP8 is purely a style guide it says nothing about
correctness. Unless you plan to submit your code for inclusion
in the Python distribution you can completely ignore PEP8 if
you wish, your code will still work.

> *Case 1)  I have to update the dict if it is empty using an if statement  .

> e = {}                          # empty dict
> if not e:
>     e.update(A=3)        # will update the dict if it is empty otherwise

Yes that's what PEP8 recommends.

> *case 2 ) I have to remove and print each item of dict in LIFO order :*
> 
> d = {"A":9, "B":6, "C":3}
> while d:
>     x = d.popitem()
>     print(x)

And that will work too, but unless you really need to empty the dict
(or even if you do) a more pythonic approach would be:

for x in d.items():
   print(x)

d = {}    # if you really need an empty dic

It's not any shorter, in fact slightly more characters,
but it avoids using a while loop for iterating a sequence.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list