features of python to be careful about

February 27, 2024

© 2024 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui(2024-02-27 12:11:26 +0000). features of python to be careful about. https://borui/blog/2024-02-27-en-features-of-python-to-be-careful-about.
@misc{
  borui2024,
  author = {borui},
  title = {features of python to be careful about},
  year = {2024},
  publisher = {borui's blog},
  journal = {borui's blog},
  url={https://borui/blog/2024-02-27-en-features-of-python-to-be-careful-about}
}

Order of elements in set and dict

Sets are unordered, so you cannot be sure in which order the items will appear.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

List slicing

slicing returns a list which is inside the original list. Not a copied list.

This is in T.A.'s answer I found it interesting.

from typing import List

def buddle_sort(lst: List):
    if len(lst) < 2:
        return lst#changed
    i = 0
    while i < len(lst) - 1:
        if lst[i+1] < lst[i]:
            lst[i], lst[i+1] = lst[i+1], lst[i]
        i += 1
    return buddle_sort(lst[:len(lst)-1])#changed to prevent returning None when if block isn't executed 


a = [100, 8, 3, 4, 6]
a = buddle_sort(a)#changed
print(a)

a[len(a):] = [1, 2]
print(a)

T. A.. (Mar 2022). Hello, @kingluo. No, slicing returns a list which is inside the original list. Not a copied list. But, in your code; there is a function which edits the parameter-list. If you are working with parameters, you must know that changes made at a parameter doesn’t effect the original variable you pass into it. To understand this better, you can try running this basic code:. [Answer]. discuss.python.org. https://discuss.python.org/t/does-the-list-slicing-produce-a-new-list/14627

Not operator

>>> # Bad practice
>>> not "c" in ["a", "b", "c"]
False

>>> # Best practice
>>> "c" not in ["a", "b", "c"]
False
>>> obj = None

>>> # Bad practice
>>> not obj is None
False

>>> # Best practice
>>> obj is not None
False

Now say you need to check if a given character is a numeric value. Since you already have NON_NUMERIC, you can think of using not to check the condition:

if char not in NON_NUMERIC:
    number = float(char)
    # Do further computations...

This code looks odd, and you probably won’t ever do something like this in your career as a programmer. However, doing something similar can sometimes be tempting, such as in the example above.

This example uses double negation. It relies on NON_NUMERIC and also on not, which makes it hard to digest and understand. If you ever get to a piece of code like this, then take a minute to try writing it positively or, at least, try to remove one layer of negation.

  1. Leodanis Pozo Ramos. (Oct 25, 2021.). Using the "not" Boolean Operator in Python. realpython. [Blog post]. Retrieved from https://realpython.com/python-not-operator/

python for in loop

for i in []:
    #code in this loop block will not be excuted

if list or set for iteration is empty, the whole loop wil be skipped, nothing in the loop will be executed

Addtional reading

  1. Vijayasekhar Deepak. (Aug 27, 2023). What happens when you apply for loop, reduce, forEach and map for empty list in Dart. Medium. [Blog post]. Retrieved from https://tarzzotech.medium.com/what-happens-when-you-apply-for-loop-reduce-foreach-and-map-for-empty-list-in-dart-92113d867094

for else in python?

else block will execute when the loop didn't exit using break keyword

  1. Helperhaps. (19 June, 2018.). Python 的 For/Else 语句. 知乎专栏. [Blog post]. Retrieved from https://zhuanlan.zhihu.com/p/37374055

Precision Handling in Python

Using format:

format(0.1, '.17f')
# output'0.10000000000000001'

Using Decimal:

from decimal import *
getcontext().prec = 6
Decimal(1) / Decimal(7)
# output Decimal('0.142857')
getcontext().prec = 28
Decimal(1) / Decimal(7)
# output Decimal('0.1428571428571428571428571429')

Using Fractions: If we want to get more precise results, we can use fractions. Fractions|Documents

Two built-in libraraies of unit test

https://docs.python.org/3/library/unittest.html

https://docs.python.org/3/library/doctest.html#module-doctest