1571107917
Python is a no-BS programming language. Readability and simplicity of design are two of the biggest reasons for its immense popularity.
This is why it is worthwhile to remember some common Python tricks to help improve your code design. These will save you the trouble of surfing Stack Overflow every time you need to do something.
The following tricks will prove handy in your day-to-day coding exercises.
The following snippet can be used to find all the unique elements in a string. We use the property that all elements in a set are unique.
my_string = "aavvccccddddeee"
# converting the string to a set
temp_set = set(my_string)
# stitching set into a string using join
new_string = ''.join(temp_set)
print(new_string)
The following snippet can be used to convert a string to title case. This is done using the title()
method of the string class.
my_string = "my name is chaitanya baweja"
# using the title() function of string class
new_string = my_string.title()
print(new_string)
# Output
# My Name Is Chaitanya Baweja
The following snippet reverses a string using the Python slicing operation.
# Reversing a string using slicing
my_string = "ABCDE"
reversed_string = my_string[::-1]
print(reversed_string)
# Output
# EDCBA
You can read more about this here.
You can use multiplication (*) with strings or lists. This allows us to multiply them as many times as we like.
n = 3 # number of repetitions
my_string = "abcd"
my_list = [1,2,3]
print(my_string*n)
# abcdabcdabcd
print(my_list*n)
# [1,2,3,1,2,3,1,2,3]
An interesting use case of this could be to define a list with a constant value — let’s say zero.
n = 4
my_list = [0]*n # n denotes the length of the required list
# [0, 0, 0, 0]
The join() method combines a list of strings passed as an argument into a single string. In our case, we separate them using the comma separator.
list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']
# Using join with the comma separator
print(','.join(list_of_strings))
# Output
# My,name,is,Chaitanya,Baweja
Python makes it quite simple to swap values between two variables without using another variable.
a = 1
b = 2
a, b = b, a
print(a) # 2
print(b) # 1
We can split a string into a list of substrings using the .split() method in the string class. You can also pass as an argument the separator on which you wish to split.
string_1 = "My name is Chaitanya Baweja"
string_2 = "sample/ string 2"
# default separator ' '
print(string_1.split())
# ['My', 'name', 'is', 'Chaitanya', 'Baweja']
# defining separator as '/'
print(string_2.split('/'))
# ['sample', ' string 2']
List comprehension provides us with an elegant way of creating lists based on other lists.
The following snippet creates a new list by multiplying each element of the old list by two.
# Multiplying each element in a list by 2
original_list = [1,2,3,4]
new_list = [2*x for x in original_list]
print(new_list)
# [2,4,6,8]
You can read more about it here.
We have already discussed how to reverse a string. So palindromes become a straightforward program in Python.
my_string = "abcba"
if my_string == my_string[::-1]:
print("palindrome")
else:
print("not palindrome")
# Output
# palindrome
The following script uses enumerate to iterate through values in a list along with their indices.
my_list = ['a', 'b', 'c', 'd', 'e']
for index, value in enumerate(my_list):
print('{0}: {1}'.format(index, value))
# 0: a
# 1: b
# 2: c
# 3: d
# 4: e
An interesting application of the Counter
class is to find anagrams.
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase.
If the Counter
objects of two strings are equal, then they are anagrams.
from collections import Counter
str_1, str_2, str_3 = "acbde", "abced", "abcda"
cnt_1, cnt_2, cnt_3 = Counter(str_1), Counter(str_2), Counter(str_3)
if cnt_1 == cnt_2:
print('1 and 2 anagram')
if cnt_1 == cnt_3:
print('1 and 3 anagram')
Error handling in Python can be done easily using the try/except block. Adding an else statement to this block might be useful. It’s run when there is no exception raised in the try block.
If you need to run something irrespective of exception, use finally
.
a, b = 1,0
try:
print(a/b)
# exception raised when b is 0
except ZeroDivisionError:
print("division by zero")
else:
print("no exceptions raised")
finally:
print("Run this always")
There are multiple ways of doing this, but my favorite is using the Python Counter
class.
Python counter keeps track of the frequency of each element in the container. Counter()
returns a dictionary with elements as keys and frequency as values.
We also use the most_common()
function to get themost_frequent
element in the list.
# finding frequency of each element in a list
from collections import Counter
my_list = ['a','a','b','b','b','c','d','d','d','d','d']
count = Counter(my_list) # defining a counter object
print(count) # Of all elements
# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
print(count['b']) # of individual element
# 3
print(count.most_common(1)) # most frequent element
# [('d', 5)]
The following script can be used to check the memory usage of an object. Read more about it here.
import sys
num = 21
print(sys.getsizeof(num))
# In Python 2, 24
# In Python 3, 28
The following snippet generates n
number of random samples from a given list using the random
library.
import random
my_list = ['a', 'b', 'c', 'd', 'e']
num_samples = 2
samples = random.sample(my_list,num_samples)
print(samples)
# [ 'a', 'e'] this will have any 2 random values
I have been recommended the secrets library for generating random samples for cryptography purposes. The following snippet will work
only on Python 3.
import secrets # imports secure module.
secure_random = secrets.SystemRandom() # creates a secure random object.
my_list = ['a','b','c','d','e']
num_samples = 2
samples = secure_random.sample(my_list, num_samples)
print(samples)
# [ 'e', 'd'] this will have any 2 random values
The following snippet uses the time
library to calculate the time taken to execute a piece of code.
import time
start_time = time.time()
# Code to check follows
a, b = 1,2
c = a+ b
# Code to check ends
end_time = time.time()
time_taken_in_micro = (end_time- start_time)*(10**6)
print(" Time taken in micro_seconds: {0} ms").format(time_taken_in_micro)
Sometimes you’re not sure about the nesting depth of your list, and you simply want all the elements in a single flat list.
Here’s how you can get that:
from iteration_utilities import deepflatten
# if you only have one depth nested_list, use this
def flatten(l):
return [item for sublist in l for item in sublist]
l = [[1,2,3],[3]]
print(flatten(l))
# [1, 2, 3, 3]
# if you don't know how deep the list is nested
l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]]
print(list(deepflatten(l, depth=3)))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Numpy flatten is a better way to do this if you have a properly formatted array.
While in Python 2, we used the update()
method to merge two dictionaries; Python 3.5 made the process even simpler.
In the script given below, two dictionaries are merged. Values from the second dictionary are used in case of intersections.
dict_1 = {'apple': 9, 'banana': 6}
dict_2 = {'banana': 4, 'orange': 8}
combined_dict = {**dict_1, **dict_2}
print(combined_dict)
# Output
# {'apple': 9, 'banana': 4, 'orange': 8}
Thanks for reading !
#python
1571402052
thanks
1585630588
Thank you!
1597272810
Nice!
1611938701
thanks
1619518440
Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.
…
#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners
1619510796
Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.
Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is
Syntax: x = lambda arguments : expression
Now i will show you some python lambda function examples:
#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map
1623077340
1. How to print “Hello World” on Python?
2. How to print “Hello + Username” with the user’s name on Python?
3. How to add 2 numbers entered on Python?
4. How to find the Average of 2 Entered Numbers on Python?
5. How to calculate the Entered Visa and Final Grade Average on Python?
6. How to find the Average of 3 Written Grades entered on Python?
7. How to show the Class Pass Status (PASSED — FAILED) of the Student whose Written Average Has Been Entered on Python?
8. How to find out if the entered number is odd or even on Python?
9. How to find out if the entered number is Positive, Negative, or 0 on Python?
…
#programming #python #coding #50+ basic python code examples #python programming examples #python code
1623056117
Python is one of the top 10 popular programming languages of 2021. Python is a general purpose and high level programming language. You can use Python for developing desktop GUI applications, websites and web applications. Also, you can use Python for developing complex scientific and numeric applications. Python is designed with features to facilitate data analysis and visualization. You can take advantage of the data analysis features of Python to create custom big data solutions without putting extra time and effort.
Currently Unity 3D developer used to code in C## because Unity 3D supports C## by default. But python is known for simplicity and rich in library support for data science. Today we are going to explore python in Unity 3D.
#unity3d #python #running your python code in unity #a python script #code in unity3d #your python cod
1626984360
with
to Open FilesWhen you open a file without the with
statement, you need to remember closing the file via calling close()
explicitly when finished with processing it. Even while explicitly closing the resource, there are chances of exceptions before the resource is actually released. This can cause inconsistencies, or lead the file to be corrupted. Opening a file via with
implements the context manager protocol that releases the resource when execution is outside of the with
block.
list
/dict
/set
Comprehension Unnecessarilyget()
to Return Default Values From a Dictionary…
#code reviews #python programming #debugger #code review tips #python coding #python code #code debugging