Python traps (written in RStudio)

Weiwei QI

2022/11/20

run python in RStudio

package required:

reticulate

reticulate::py_config()$version_string
## [1] "3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)]"

trap 1: I am trying to append, but

issue

case1 = [5, 4, 3, 2]

case1 = case1.append(1)

print(case1)

fix

# fix
case1 = [5, 4, 3, 2]

case1.append(1)

print(case1)
## [5, 4, 3, 2, 1]

trap 2: (do not) modify the iterable obj in loops

issue

case2 = [9, 8, 8, 3, 3, 1]

for i in case2:
    print(i)
    if i % 2 == 0:
        case2.remove(i)
## 9
## 8
## 3
## 3
## 1
print(case2) # why is there an 8 left?
## [9, 8, 3, 3, 1]

fix

# fix list comp (personal favorite)

case2_fix = [x for x in case2 if x % 2 != 0]

print(case2_fix)
## [9, 3, 3, 1]

trap 3: the ignored comma

issues

case3 = ['a', 'b', 'c', 'd', 'e']

print(len(case3))
case3 = ['a', 
         'b' 
         'c', 
         'd', 
         'e']

print(case3)
print(len(case3))

caveat

strbc = 'b' 'c' # 'b'+'c' equivalent
print(strbc)
## bc

trap 4: my one-element tuple is not a tuple (tuple is kinda like a list, only immutable)

Suppose we want an one element tuple, and tuple is defined with brackets

issue

case4 = ('DATASCIENCE')

for i in case4:
    print(i)
## D
## A
## T
## A
## S
## C
## I
## E
## N
## C
## E
type(case4) # not correct
## <class 'str'>

try

case4 = tuple('DATASCIENCE')

type(case4)
## <class 'tuple'>
for i in case4:
    print(i)
## D
## A
## T
## A
## S
## C
## I
## E
## N
## C
## E

fix

case4_fix = ('DATASCIENCE', ) # add a comma if you are defining an one-element tuple
type(case4_fix)
## <class 'tuple'>
for i in case4_fix:
    print(i)
## DATASCIENCE

trap 5 python one-liner | the half-good

flag = False

if flag:
    x, y = 10, 10
else: 
    x, y = None, None

print(x, y)
## None None

all good (?)

# python one liner

x, y = (10, 10) if flag else None, None # works when flag is False
print(x, y)
## None None

half-good

flag = True

x, y = (10, 10) if flag else None, None # it does not work!!!
print(x, y)
## (10, 10) None

fix

# fix one liner

x, y = (10, 10) if flag else (None, None)
print(x, y)
## 10 10