I made a C++ tricks post and I wanted to write about a lot more of tricks that I know, since most of them are in Python and JS even though I have coded in C++ a lot more but anyways here they are, I'll start with trivial things about basic Python syntax but there are some things that are not known to beginners, which I've marked with a star ⭐️:
An easy way to access subarrays of a list
Modifying one also modifies the other since both are same memory allocations
3 ways:
I will start off with some basic list comprehensions, but they'll quickly get less trivial.
values = [word for word in values if len(word) > 1 and word[0] == 'a' and word[-1] == 'y'] # OR, a nicer way is ⭐️ values = [ string for string in values if len(string) > 1 if string[0] == 'a' if string[-1] == 'y' ]
Flattening a list of lists, or a 2D matrix
Nested list comprehension: Flattening a matrix (a list of lists) ⭐️
Example: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
values = [ number for row in matrix for number in row ] # first for loop then the next for loop is inside the first and so on
values = [ "Even" if x % 2 == 0 else "Odd" for x in range(10) ]
This syntax ->
"Even" if x % 2 == 0 else "Odd" is valid in a lot of places in python, you can also put it in variables, this is basically a ternary operator but more verbose
⭐️ For understanding any list comprehension always look on the left and the right side of the expression, any nested loops go from left to right, when the if else is on the left of the for loop we check what value do we wanna insert depending on the if else condition, whereas when the for loop is on the right we are trying to filter from the list
For example to create a 5x5x5 list: ⭐️
values = [[[num+1 for num in range(5)] for _ in range(5)] for _ in range(5)]
⭐️ Look for the exterior most for loop, whatever is to its left will get added to the values[] array, and the meaning of this syntax: for _ in range(5) is that I want to do whatever is on the left of this for loop 5 times (because I don't care about the value of the iterator variable at each iteration)
If we have pairs = [("a", 1), ("b", 2)]: a list of pairs or tuples
-> my_dict = {k:v for k, v in pairs}: value unpacking, for this to work, each "pair" in pairs must have exactly 2 entities
Let nums = [1, 2, 3, 1, 3, 2, 4, 2, 1, 3]
unique_nums = {x for x in nums}: python will know that this should be a set because you don't have any keys
I will write this once I get some time, but you can still check them out here: AdvancedPythonConcepts this is my git repo where I documented python concepts when I first learnt them. I will write this post based off of this repo once I get the time...
The above is the detailed content of Python notes/tricks/lessons/nuances. For more information, please follow other related articles on the PHP Chinese website!