Some wonderful Python code snippets, let us have a broader understanding of some details in Python
wtfPython is a project on github. The author has collected some wonderful Python code snippets. The output results of these codes will be different from what we imagined; by exploring the internal reasons for this result, we can learn about the Some details are more widely understood.
1. Implicit conversion of dictionary keys
some_dict = {}some_dict[5.5] = "Ruby"some_dict[5.0] = "JavaScript"some_dict[5] = "Python"
The output is as follows:
>>> some_dict{5.0: "Python", 5.5: "Ruby"}>>> some_dict[5.5]"Ruby">>> some_dict[5.0]"Python">>> some_dict[5]"Python"
the reason:
Python's dictionary keys are compared by hash values. In Python, if the values ​​of two immutable objects are equal, their hashes are also the same, so here hash(5) == hash(5.0) is True , So the key is implicitly converted
2. The difference in generator execution time
array = [1, 8, 15]g = (x for x in array if array.count(x)> 0)array = [2, 8, 22]
Output:
>>> print(list(g))[8]
the reason
In a generator expression, the operation of in is evaluated at the time of declaration, and if is evaluated at runtime, the array has been reassigned to [2,8,22],x before the runtime. The value of is also 2, 8, 22
3. Iteratively delete items in the list
list_1 = [1, 2, 3, 4]list_2 = [1, 2, 3, 4]list_3 = [1, 2, 3, 4]list_4 = [1, 2, 3, 4]for idx, item in enumerate (list_1): del itemfor idx, item in enumerate(list_2): list_2.remove(item)for idx, item in enumerate(list_3[:]): list_3.remove(item)for idx, item in enumerate(list_4): list_4.pop(idx)
Output:
>>> list_1[1, 2, 3, 4]>>> list_2[2, 4]>>> list_3[]>>> list_4[2, 4]
the reason
In fact, only list3 is considered qualified. Modifying an object that is iterating is not a good choice. The correct way is to create a copy of the object to iterate. For list1, del item deletes only the item variable. Rather than the data pointed to by the variable, it has no effect on the list itself. For list2 and list4, because the iteration of the list is based on the index, the 1 with index 0 is deleted for the first time, leaving [2, 3, 4], and then Remove index 1 (3 at this time), leaving [2, 4], now there are only 2 elements, and the loop ends
4. Else different treatment
For looping else
def does_exists_num(l, to_find): for num in l: if num == to_find: print("Exists!") break else: print("Does not exist")
Output:
>>> some_list = [1, 2, 3, 4, 5]>>> does_exists_num(some_list, 4)Exists!>>> does_exists_num(some_list, -1)Does not exist
For try else
try: passexcept: print("Exception occurred!!!")else: print("Try block executed successfully...")
Output:
Try block executed successfully...
the reason
The else after the loop will only be executed when all iterations have passed and no break occurs. The else after the try module will be executed after the code in the try is successfully executed.
5.is in python
>>> a = 256>>> b = 256>>> a is bTrue>>> a = 257>>> b = 257>>> a is bFalse
the reason
is and == are not the same; is judges whether two objects are the same object, and == judges whether the values ​​of the two objects are equal; that is, is requires equal values ​​and consistent references in Python -5~256 is designed as a fixed object because it is often used
6. Leakage of local variables in loops
Code snippet 1
for x in range(7): if x == 6: print(x,': for x inside loop')print(x,': x in global')
Output:
6: for x inside loop 6: x in global
Code snippet 2
# This time let's initialize x firstx = -1for x in range(7): if x == 6: print(x,': for x inside loop')print(x,': x in global')
Output:
6: for x inside loop 6: x in global
Code snippet 3
x = 1print([x for x in range(5)])print(x,': x in global')
The output in Python 2.x:
[0, 1, 2, 3, 4](4,': x in global')
The output in Python 3.x:
[0, 1, 2, 3, 4]1: x in global
the reason
For code segment 1, in Python, for loops can use variables in their namespace and save the loop variables they define; * for code segment 2, if we display the definition of for loop variables in the global namespace , The loop variable will be bound to the existing variable again. For code segment 3, the grammatical form of list comprehension has been changed in Python3.x; in Python2.x, the grammatical form of list comprehension is: [... for var in item1, item2, …]; and list comprehension in Python3.x The formula is: [… for var in (item1, item2, …)], in this case there will be no leakage of loop variables
7. The difference between + and +=
Code snippet 1
a = [1, 2, 3, 4]b = aa = a + [5, 6, 7, 8]
Output:
>>> a[1, 2, 3, 4, 5, 6, 7, 8]>>> b[1, 2, 3, 4]
Code snippet 2
a = [1, 2, 3, 4] b = aa += [5, 6, 7, 8]
Output:
>>> a[1, 2, 3, 4, 5, 6, 7, 8]>>> b[1, 2, 3, 4, 5, 6, 7, 8]
the reason
The operation of a = a + b generates a new object and establishes a new reference a += b is an extend operation on the a list
8. About return in try-finally
def some_func(): try: return'from_try' finally: return'from_finally'
Output:
>>> some_func()'from_finally'
the reason
In try...finally, the return statement in finally is always the last one to execute a function. The value of return is determined by the last return statement.
9.True=False
True = Falseif True == False: print("I've lost faith in truth!")
Output:
I've lost faith in truth!
the reason
At the beginning, Python did not have the bool type (using 0 for false and non-zero value for true), and later added the True, False and bool types; but for backward compatibility, True and False are not set It is a constant, but just a built-in variable, so it can be assigned and modified in Python3, because it is not backward compatible, so this will not happen
10. One step operation, from there to nothing
some_list = [1, 2, 3]some_dict = {"key_1": 1, "key_2": 2, "key_3": 3}some_list = some_list.append(4)some_dict = some_dict.update({"key_4": 4 })
Output:
>>> print(some_list)None>>> print(some_dict)None
Reasons Many methods of modifying sequence/mapping objects (such as list.append, dict.update, list.sort, etc.) are to directly modify the object and return a None; therefore, you should avoid direct assignment when encountering such direct modification operations. .
11.Python for
for i in range(4): print(i) i = 10
Output:
0123
the reason
Python's for loop mechanism is to unpack and assign once every iteration to the next item; that is, the four values ​​in range(4) will be unpacked and assigned once every iteration; so i = 10 pairs Iteration has no effect.
I-Beam Inductors,Chip Inductors,Color Ring Inductor,R-Bar Inductors
Shenzhen Sichuangge Magneto-electric Co. , Ltd , https://www.scginductor.com