Python is an interpreted language, and its readability and ease of use make it more and more popular.
As stated in The Zen of Python:
Beautiful is better than ugly, clear is better than obscure.
In your daily coding, the following tips can bring you unexpected gains.
string reverse
The following code snippet uses the slicing operation in Python to achieve string reversal:
1# Reversing a string using slicing
2
3my_string = "ABCDE"
4reversed_string = my_string[::-1]
5
6print(reversed_string)
7
8# Output
9# EDCBA
In this article (https://medium.com/swlh/how-to-reverse-a-string-in-python-66fc4bbc7379), you can learn more details.
capitalized
The following code fragment can capitalize the first letter of a string, using title()
the methods of the String class:
1my_string = "my name is chaitanya baweja"
2
3# using the title() function of string class
4new_string = my_string.title()
5
6print(new_string)
7
8# Output
9# My Name Is Chaitanya Baweja
Get the elements that make up the string
The following code snippet can be used to find out all the elements that make up a string. We use the feature that only unique elements can be stored in the set :
1my_string = "aavvccccddddeee"
2
3# converting the string to a set
4temp_set = set(my_string)
5
6# stitching set into a string using join
7new_string = ''.join(temp_set)
8
9print(new_string)
10
11# Output
12# acedv
Repeat output String/List
String/List can be multiplied. This method can be used to multiply them arbitrarily.
1n = 3 # number of repetitions
2my_string = "abcd"
3my_list = [1,2,3]
4
5print(my_string*n)
6# abcdabcdabcd
7
8print(my_string*n)
9# [1,2,3,1,2,3,1,2,3]
An interesting usage is to define a list of n constants:
1n = 4
2my_list = [0]*n # n represents the length of the required list
3# [0, 0, 0, 0]
list comprehension
List comprehensions provide a more elegant way of working with lists.
In the following code snippet, the elements in the old list are multiplied by 2 to create the new list:
1original_list = [1,2,3,4]
2
3new_list = [2*x for x in original_list]
4
5print(new_list)
6# [2,4,6,8]
swap two variable values
Python swaps the values of two variables without creating an intermediate variable, it's easy to do:
1a = 1
2b = 2
3
4a, b = b, a
5
6print(a) # 2
7print(b) # 1
string split
Use split()
the method to split a string into multiple substrings, and you can also pass the separator as a parameter for splitting.
1string_1 = "My name is Chaitanya Baweja"
2string_2 = "sample/ string 2"
3
4# default separator ' '
5print(string_1.split())
6# ['My', 'name', 'is', 'Chaitanya', 'Baweja']
7
8# defining separator as '/'
9print(string_2.split('/'))
10# ['sample', ' string 2']
string concatenation
join()
The method can combine a list of strings into a string. In the following code snippet, I use ,
to concatenate all the strings together:
1list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']
2
3# Using join with the comma separator
4print(','.join(list_of_strings))
5
6# Output
7# My,name,is,Chaitanya,Baweja
Palindrome detection
Earlier, we have said how to flip a string, so palindrome detection is very simple:
1my_string = "abcba"
2
3if my_string == my_string[::-1]:
4 print("palindrome")
5else:
6 print("not palindrome")
7
8# Output
9# palindrome
element repetitions
There are many ways to do this in Python, but my favorite is Counter
this class.
Counter
The number of occurrences of each element will be counted, and Counter()
a dictionary will be returned, with the element as the key and the number of occurrences as the value.
We can also use most_common()
this method to get the element with the most words.
1from collections import Counter
2
3my_list = ['a','a','b','b','b','c','d','d','d','d','d']
4count = Counter(my_list) # defining a counter object
5
6print(count) # Of all elements
7# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
8
9print(count['b']) # of individual element
10# 3
11
12print(count.most_common(1)) # most frequent element
13# [('d', 5)]
anagram
Counter
An interesting use of anagrams is to find anagrams :
An anagram is a new word formed by changing the position (order) of letters in a word or sentence.
If Counter
the two resulting objects are equal, they are anagrams:
1from collections import Counter
2
3str_1, str_2, str_3 = "acbde", "abced", "abcda"
4cnt_1, cnt_2, cnt_3 = Counter(str_1), Counter(str_2), Counter(str_3)
5
6if cnt_1 == cnt_2:
7 print('1 and 2 anagram')
8if cnt_1 == cnt_3:
9 print('1 and 3 anagram')
try-except-else
In Python, use try-except for exception capture. else can be used to execute when no exception occurs.
If you need to execute some code regardless of whether an exception occurred, use final:
1a, b = 1,0
2
3try:
4 print(a/b)
5 # exception raised when b is 0
6except ZeroDivisionError:
7 print("division by zero")
8else:
9 print("no exceptions raised")
10finally:
11 print("Run this always")
enumeration traversal
In the following code snippet, iterate over the values and corresponding indices in the list:
1my_list = ['a', 'b', 'c', 'd', 'e']
2
3for index, value in enumerate(my_list):
4 print('{0}: {1}'.format(index, value))
5
6# 0: a
7# 1: b
8# 2: c
9# 3: d
10# 4: e
object memory size
The following code snippet shows how to get the memory size occupied by an object:
1import sys
2
3num = 21
4
5print(sys.getsizeof(num))
6
7# In Python 2, 24
8# In Python 3, 28
merge two dictionaries
In Python 2, use update()
the method to merge. In Python 3.5, it is simpler. In the following code snippet, two dictionaries are merged. When the two dictionaries overlap, the latter one is used to overwrite.
1dict_1 = {'apple': 9, 'banana': 6}
2dict_2 = {'banana': 4, 'orange': 8}
3
4combined_dict = {**dict_1, **dict_2}
5
6print(combined_dict)
7# Output
8# {'apple': 9, 'banana': 4, 'orange': 8}
code execution time
In the following code snippet, time
this library is used to calculate the execution time of the code:
1import time
2
3start_time = time.time()
4# Code to check follows
5a, b = 1,2
6c = a+ b
7# Code to check ends
8end_time = time.time()
9time_taken_in_micro = (end_time- start_time)*(10**6)
10
11print(" Time taken in micro_seconds: {0} ms").format(time_taken_in_micro)
list expanded
Sometimes, you don't know the nesting depth of your current list, but you want to expand them into a one-dimensional list. Here's how to do it:
1from iteration_utilities import deepflatten
2
3# if you only have one depth nested_list, use this
4def flatten(l):
5 return [item for sublist in l for item in sublist]
6
7l = [[1,2,3],[3]]
8print(flatten(l))
9# [1, 2, 3, 3]
10
11# if you don't know how deep the list is nested
12l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]
13
14print(list(deepflatten(l, depth=3)))
15# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Numpy flatten can handle your formatted data better.
random sampling
The following example random
implements random sampling from a list using the library.
1import random
2
3my_list = ['a', 'b', 'c', 'd', 'e']
4num_samples = 2
5
6samples = random.sample(my_list,num_samples)
7print(samples)
For random sampling, I recommend using secrets
a library to achieve it, which is safer. The following code snippet will only work in Python 3:
1import secrets # imports secure module.
2secure_random = secrets.SystemRandom() # creates a secure random object.
3
4my_list = ['a','b','c','d','e']
5num_samples = 2
6
7samples = secure_random.sample(my_list, num_samples)
8
9print(samples)
Digitizing
The following code converts an integer into a digitized object:
1num = 123456
2
3list_of_digits = list(map(int, str(num)))
4
5print(list_of_digits)
6# [1, 2, 3, 4, 5, 6]
uniqueness check
The following code example can check whether the elements in the list are unique:
1def unique(l):
2 if len(l)==len(set(l)):
3 print("All elements are unique")
4 else:
5 print("List has duplicates")
6
7unique([1,2,3,4])
8# All elements are unique
9
10unique([1,1,2,3])
11# List has duplicates
Summarize
These are codes that I find very useful in my daily work. Thank you very much for reading this article, I hope it will be helpful to you. Here I still want to recommend the Python learning Q group I built myself: 831804576. Everyone in the group is learning Python. If you want to learn or are learning Python, you are welcome to join. Everyone is a software development party and shares dry goods from time to time ( Only related to Python software development),
including a 2022 latest Python advanced material and zero-based teaching compiled by myself, welcome advanced and interested friends to join in Python!