Thursday, December 26, 2024
Google search engine
HomeLanguages10 Python Code Snippets For Everyday Programming Problems

10 Python Code Snippets For Everyday Programming Problems

In recent years, the Python programming language has seen a huge user base. One of the reasons could be that it is easier to learn as compared to other object-oriented programming languages like Java, C++, C#, JavaScript, and therefore more and more beginners who are entering the field of computer science are opting for Python. Another reason why the popularity of Python has shot up is that it is used in almost all domains of the IT industry, be it data science, machine learning, automation, web scraping, artificial intelligence, cyber-security, cloud computing, and what not! According to the recent developer survey, it is seen that Python is currently the second most loved programming language after JavaScript and will easily shoot up in the coming years. Demand for Python developers has significantly risen, especially in the past few months, and therefore learning Python could get you some really good career options.

10-Python-Code-Snippets-For-Programming-Problems

So if you are a Python developer, this article is definitely for you. Today we are going to discuss Python code snippets with their brief explanation that are highly useful for developers and programmers in their day-to-day life. We will look at various coding problems that arise on a regular basis and how to solve them using the Python code snippets provided here. So let’s get started!

1. List Comprehension Using If-Else

List comprehensions in Python are super helpful and powerful. They reduce the code length to a great length and make it more readable. In the following code, we can see that we are checking multiples of 6, and then multiples of 2 and 3 using the if-else conditions inside the list, which reduced the code to a great extent.

Python3




my_list = ['Multiple of 6' if i % 6 == 0 
           else 'Multiple of 2' if i % 2 == 0 
           else 'Multiple of 3' if i % 3 == 0 
           else i for i in range(1, 20)]
print(my_list)


Output:

[1, ‘Multiple of 2’, ‘Multiple of 3’, ‘Multiple of 2’, 5, ‘Multiple of 6’, 7, ‘Multiple of 2’, ‘Multiple of 3’, ‘Multiple of 2’, 11, ‘Multiple of 6’, 13, ‘Multiple of 2’, ‘Multiple of 3’, ‘Multiple of 2’, 17, ‘Multiple of 6’, 19]

2. Merging Two Dictionaries

It may sound very confusing to merge two dictionaries or append them. But surprisingly, there is more than one method where you can merge two dictionaries. In the following code, the first method uses dictionary unpacking where the two dictionaries unpack together into result. In the second method, we first copy the first dictionary into the result and then update it with the content of the second dictionary. The third method is a straightforward implementation using dictionary comprehension, similar to what we saw in list comprehension above.

Python3




my_dict1 = {'a' : 1, 'b' : 2, 'c' : 3}
my_dict2 = {'d' : 4, 'e' : 5, 'f' : 6}
  
# Method 1
result = { **my_dict1, **my_dict2}
print(result)
  
# Method 2
result = my_dict1.copy()
result.update(my_dict2)
print(result)
  
# Method 3
result = {key: value for d in (my_dict1, my_dict2) for key, value in d.items()}
print(result)


Output:

{‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4, ‘e’: 5, ‘f’: 6}

{‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4, ‘e’: 5, ‘f’: 6}

{‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4, ‘e’: 5, ‘f

3. File Handling

File handling is used in various Python programs, especially the ones related to data where we need to read huge comma-separated values. File handling has various operations like opening a file, reading from a file, writing to a file, and closing a file.

Python3




# Open a file
f = open('filename.txt')
  
  
# Read from a file
f = open('filename.txt', 'r')
  
# To read the whole file
print(f.read())
  
# To read single line
print(f.readline())
  
  
# Write to a file
f = open('filename.txt', 'w')
f.write('Writing into a file \n')
  
  
# Closing a file
f.close()


4. Calculating Execution Time

It is often necessary to optimize code and analyze performance metrics. Here, the time library comes to help. We can measure the runtime of our code and optimize it. We can also use it to measure the runtime of two pieces of code doing the same work so that we can choose the most optimized one. 

Python3




import time
  
start_time = time.time()
  
# printing all even numbers till 20
for i in range(20):
  if i % 2 == 0:
    print(i, end = " ")
  
end_time = time.time()
time_taken = end_time - start_time
print("\nTime: ", time_taken)


Output:

0 2 4 6 8 10 12 14 16 18

Time:  2.47955322265625e-05

5. Sorting a List of Dictionaries

Sorting a list of dictionaries sounds daunting at first but we can do it using two different, yet similar approaches. We can simply use the in-built sorted() or sort() function which works on lists using a lambda function inside it which sorts the dictionaries based on their ‘id’ key. In the first method, the return type is None as the changes are in place, on the other hand, in the second method, a new list of sorted dictionaries is returned.

Python3




person = [
  {
    'name' : 'alice',
    'age' : 22,
    'id' : 92345
  },
  {
    'name' : 'bob',
    'age' : 24,
    'id' : 52353
  },
  {
    'name' : 'tom',
    'age' : 23,
    'id' : 62257
  }
]
  
# Method 1
person.sort(key=lambda item: item.get("id"))
print(person)
  
# Method 2
person = sorted(person, key=lambda item: item.get("id"))
print(person)


Output:

[{‘name’: ‘bob’, ‘age’: 24, ‘id’: 52353}, {‘name’: ‘tom’, ‘age’: 23, ‘id’: 62257}, {‘name’: ‘alice’, ‘age’: 22, ‘id’: 92345}]

[{‘name’: ‘bob’, ‘age’: 24, ‘id’: 52353}, {‘name’: ‘tom’, ‘age’: 23, ‘id’: 62257}, {‘name’: ‘alice’, ‘age’: 22, ‘id’: 92345}]

6. Finding Highest Frequency Element

We can find the element, which occurs the maximum time, by passing the key as the count of elements, i.e., the number of times they appear. 

Python3




my_list = [8,4,8,2,2,5,8,0,3,5,2,5,8,9,3,8]
print("Most frequent item:", max(set(my_list), key=my_list.count))


Output:

Most frequent item: 8

7. Error Handling

Error handling is the use of try-catch (and finally) to eradicate any possibilities of sudden stoppage while executing. The statement which can cause an error is put into a try block, which is followed by an except block which catches the exception (if any), and then we have the ‘finally’ block which executes no matter what and is optional. 

Python3




num1, num2 = 2,0
try:
    print(num1 / num2)
except ZeroDivisionError:
    print("Exception! Division by Zero not permitted.")
finally:
    print("Finally block.")


Output:

Exception! Division by Zero not permitted.

Finally block.

8. Finding Substring in List of Strings

This is again a very common piece of code that Python programmers encounter very often. If we need to find substrings inside a list of strings (can also be applied on larger strings rather than just lists), we can use the find() method which returns -1 if the value is not present in the string, or returns the first occurrence. In the second method, we can directly use the in operator to see if the desired substring is present in the string.

Python3




records = [
  "Vani Gupta, University of Hyderabad",
  "Elon Musk, Tesla",
  "Bill Gates, Microsoft",
  "Steve Jobs, Apple"
]
  
# Method 1
name = "Vani"
for record in records:
    if record.find(name) >= 0:
        print(record)
  
# Method 2
name = "Musk"
for record in records:
    if name in record:
        print(record)


Output:

Vani Gupta, University of Hyderabad

Elon Musk, Tesla

9. String Formatting

String formatting is used to format or modify strings. There are a lot of ways in which string formatting can be done. In the first method, we use basic concatenation which simply adds the strings together. In the second method, we use f-strings, where the variable name is written in braces and is replaced during runtime. Similar to the second method, we have the third method, where we use %s, where the s signifies that it is a string, and in the fourth method, we use the format() function which takes the string or variable to be inserted in the string as an argument and places it wherever it sees a curly brace.

Python3




language = "Python"
  
# Method 1
print(language + " is my favourite programming language.")
  
# Method 2
print(f"I code in {language}")
  
# Method 3
print("%s is very easy to learn." % (language))
  
# Method 4
print("I like the {} programming language.".format(language))


Output:

Python is my favourite programming language.

I code in Python

Python is very easy to learn.

I like the Python programming language.

10. Flattening a List

To flatten or spread a list that contains other lists of variable lengths and numbers, we can use the append() and extend() methods and keep adding that to the new list. The difference between the two methods is that append() adds a single variable to the end of the list such that the length of the list increases by one whereas extends() adds all the elements in the list passed as argument one by one to the end of the original list.

Python3




ugly_list = [10,12,36,[41,59,63],[77],81,93]
flat = []
for i in ugly_list:
    if isinstance(i, list): flat.extend(i)
    else: flat.append(i)
print(flat)


These were a few Python code snippets that come in regular use if you’re working with the Python programming language. Hope you found these useful!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments