Python is my favorite programming language. Easy to use, readable syntax, minimal, and powerful libraries are just some reasons that I and many others love it. Also, many people who just want to try out programming start with Python due to its easy syntax and high level.
In this episodic post, I introduce some simple but handy hints that hopefully help you to better enjoy coding with Python.
Using .get for dictionaries
In one of the previous posts, I explain Python dictionaries and how to use them. One of the things that is worth reminding and remembering is dictionary access. Always use .get function instead of the direct access key.
my_dict = {'name': 'John'}
my_dict['name']
my_dict.get('name')
Both of them return ‘John’ in this case. However, if the key does not exist, the first access raises an exception but the second access with the get function returns None.
my_dict = {'name': 'John'}
my_dict['firstname'] # raises keyerror
my_dict.get('firstname') # returns None
Insert in the middle of a string with .format()
This is very handy. Many times happens that we need to format a string by adding a dynamic input that changes. We can use normal concatenation with + but using the format function increases the code simplicity and it is easier to use.
print("This is the post number {} of this blog".format(22))
Output:
This is the post number 22 of this blog
You can read more detail here.
Initiate a List with a certain default value
This is also common. Giving a default value to a list with a certain length:
my_list = 10 * [-1]
List would be:
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
Fancy? 🙂
One Line For Loop
This is extremely handy in coding with Python. Let’s say you want to create a list of numbers from one to ten. You can do it with a one-line for-loop! Yes true. Only one line:
range_list = [number for number in range(1, 11)]
List would be:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
You can do whatever operation on the number before putting it in the list:
range_list = [number/2 for number in range(1, 11)]
List would be:
[0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]
Great. Ha?
Append to a list
This is easy but worth mentioning. Sometimes you are dealing with a list that you don’t know what is the length of it. In this case, we cannot use an index to insert a new member. Here we use the append function.
my_list = []
my_list[0] = 2 # raises index out of range error
my_list.append(2) # adds the number 2 to the list
Hope you find these tips useful!
The End.