DEV Community

Cover image for Instructive Python code examples for Beginners
Vadim Kolobanov for Abstract

Posted on • Edited on • Originally published at dev.to

Instructive Python code examples for Beginners

Photo by Pakata Goh on Unsplash

Hi guys! I want to show you beautiful and instructive python code examples. Using them in training, you will discover new language features and your code will look more professional.
Let's get started!

1. We get vowels

This example returns the found vowels "a e i o u" in the string. This can be useful when searching for or detecting vowels.

def get_vowels(String):
    return [each for each in String if each in "aeiou"]
get_vowels("animal") # [a, i, a]
get_vowels("sky") # []
get_vowels("football") # [o, o, a]
Enter fullscreen mode Exit fullscreen mode

2. The first letter in uppercase

This works with a string of one or more characters and will be useful when analyzing text or writing data to a file. You can refine this code and make all letters uppercase to use case-independent search.

def capitalize(String):
    return String.title()
capitalize("shop") # [Shop]
capitalize("python programming") # [Python Programming]
capitalize("how are you!") # [How Are You!]
Enter fullscreen mode Exit fullscreen mode

3. Print the line N times

Loops are a hard part of the language. You don't have to use them to output strings.

Look how it's easy

n=5
string="Hello World "
print(string * n)  #Hello World Hello World Hello World Hello World Hello World
Enter fullscreen mode Exit fullscreen mode

4. Combine two dictionaries

Many of you guys, in order to combine 2 sequences, start overwriting one into the other. And again cycles, conditions, append and other horror... Catch a life hack, and please learn correctly!

def merge(dic1,dic2):
    return {**dic1,**dic2}
dic1={1:"Hello", 2:"Dev"}
dic2={2:"Python", 4:"Programming"}
# In these examples, Python merges dictionary keys
# in the order listed in the expression, overwriting 
# duplicates from left to right.
merge(dic1,dic2) # {1: 'Hello', 2: 'Dev', 3: 'Python', 4: 'Programming'}
Enter fullscreen mode Exit fullscreen mode

5. Calculate the execution time

This example is useful when you need to know how long it takes to execute a program or function.

import time
start_time= time.time()
def fun():
    a=2
    b=3
    c=a+b
fun()
end_time= time.time()
timetaken = end_time - start_time
print("Your program takes: ", timetaken) # 0.0345
# I love you Dev =) 
Enter fullscreen mode Exit fullscreen mode

6. Exchange of values between variables

Learn to use fewer variables guys. This option will look more elegant

a=3
b=4
a, b = b, a
print(a, b) # a= 4, b =3

Enter fullscreen mode Exit fullscreen mode

7. Checking duplicates

Here I draw attention once again to the fact that set contains immutable data. Just remember this

def check_duplicate(lst):
    return len(lst) != len(set(lst))
check_duplicate([1,2,3,4,5,4,6]) # True
check_duplicate([1,2,3]) # False
check_duplicate([1,2,3,4,9]) # False

Enter fullscreen mode Exit fullscreen mode

8. Filtering False values (or other)

An easy way to remove values from the list. Beautiful, elegant, and will show your code as the work of a professional.


def Filtering(lst):
    return list(filter(None,lst))
lst=[None,1,3,0,"",5,7]
Filtering(lst) #[1, 3, 5, 7]

Enter fullscreen mode Exit fullscreen mode

9. Size in bytes

This example returns the length of a string in bytes, which is convenient when you need to know the size of a string variable.


def ByteSize(string):
    return len(string.encode("utf8"))
ByteSize("Python") #6
ByteSize("Data") #4

Enter fullscreen mode Exit fullscreen mode

10. Load memory

It will be useful if you want to keep track of the memory that your variables occupy. The main thing is to remember:
Simple is better than complex.
Complex is better than complicated.


import sys
var1="Python"
var2=100
var3=True
print(sys.getsizeof(var1)) #55
print(sys.getsizeof(var2)) #28
print(sys.getsizeof(var3)) #28

Enter fullscreen mode Exit fullscreen mode

does not work with a recursive function

11. Anagrams

This code is useful for finding Anagrams. An anagram is a word obtained by rearranging the letters of another word.


from collections import Counter
def anagrams(str1, str2):
    return Counter(str1) == Counter(str2)
anagrams("abc1", "1bac") # True

Enter fullscreen mode Exit fullscreen mode

12. Sorting the list

This example sorts the list. Sorting is a frequently used task that can be implemented with many lines of code with a loop, but you can speed up your work using the built-in sorting method. Study Python deeper! And you will be happy.


my_list = ["leaf", "cherry", "fish"]
my_list1 = ["D","C","B","A"]
my_list2 = [1,2,3,4,5]

my_list.sort() # ['cherry', 'fish', 'leaf']
my_list1.sort() # ['A', 'B', 'C', 'D']
print(sorted(my_list2, reverse=True)) # [5, 4, 3, 2, 1]

Enter fullscreen mode Exit fullscreen mode

13. Converting a comma-separated list to a string

This code converts a comma-separated list into a single string. It is very convenient to list all the values of the list in one line. And besides, JOIN is a useful method in python

my_list1=["Python","JavaScript","C++"]
my_list2=["Java", "Flutter", "Swift"]
#example 1
"My favourite Programming Languages are" , ", ".join(my_list1))
#My favourite Programming Languages are Python, JavaScript, C++
print(", ".join(my_list2))  # Java, Flutter, Swift

Enter fullscreen mode Exit fullscreen mode

14. Shuffling the list

Everything is clear from the name here. But you didn't know that, did you? Really?

from random import shuffle
my_list1=[1,2,3,4,5,6]
my_list2=["A","B","C","D"]
shuffle(my_list1) # [4, 6, 1, 3, 2, 5]
shuffle(my_list2) # ['A', 'D', 'B', 'C']
Enter fullscreen mode Exit fullscreen mode

15 Splitting into fragments

This example will show how to split the list into fragments and divide it into smaller parts. Not so useful, but interesting


def chunk(my_list, size):
    return [my_list[i:i+size] for i in range(0,len(my_list), size)]
my_list = [1, 2, 3, 4, 5, 6]
chunk(my_list, 2) # [[1, 2], [3, 4], [5, 6]]

Enter fullscreen mode Exit fullscreen mode

Put on Heart if you liked it and you learned something new!

You can also follow ME to receive notifications about new interesting articles.

FAQ

I am a beginner, how should I learn Python?

Look into the following series:

Learning Python
Step by Step to Junior
Ideas

Would you mentor me?

Of course I am ready to participate in the training. The big difficulty is that English is not my native language and it will be possible to communicate through a translator. Write to discord, please. We have a discord community for you

Would you like to collaborate on our organization?

If you have interesting ideas, we will be happy to invite your writing from our organization. Write in private messages or in social networks below

If you have interesting projects and you need a backend developer, then you can contact me by mail or in discord for cooperation

Connect to me on

Write me on Face....oh...Meta

My Twitter

Discord: vadimkolobanov#5875

Be responsive! Mark your interest in others and others will mark you!

Top comments (3)

Collapse
 
ranggakd profile image
Retiago Drago

Since I love dict, number #4 could be one liner like this ๐Ÿš€

def merge(dic1,dic2):
    return {**dic1,**dic2}
dic1={1:"Hello", 2:"Dev"}
dic2={2:"Python", 4:"Programming"}
# In these examples, Python merges dictionary keys
# in the order listed in the expression, overwriting 
# duplicates from left to right.
merge(dic1,dic2) # {1: 'Hello', 2: 'Python', 4: 'Programming'}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vadimkolobanov profile image
Vadim Kolobanov

A very beautiful option) Thanks. I'll replace this if you don't mind)

Collapse
 
ranggakd profile image
Retiago Drago

I'll be honoured โœŒ