Python Codes
6.29K subscribers
51 photos
1 file
86 links
This channel will serve you all the codes and programs which are related to Python.

We post the codes from the beginner level to advanced level.
Download Telegram
#Basics

Return Multiple Values From Functions.

Code:
def x():
return 1, 2, 3, 4
a, b, c, d = x()

Input:
print(a, b, c, d)

Output:
1 2 3 4

Share and Support
@Python_Codes
#Basics

Find The Most Frequent Value In A List

Code:
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))

Output:
4
Share and Support
@Python_Codes
#Basics

Check The Memory Usage Of An Object.

Code:
import sys
x = 1
print(sys.getsizeof(x))

Output:
28

Share and Support
@Python_Codes
#Basics

Checking if two words are anagrams

Code:
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)

# or without having to import anything
def is_anagram(str1, str2):
return sorted(str1) == sorted(str2)

print(is_anagram('code', 'doce'))
print(is_anagram('python', 'yton'))

Output:
True
False

Share and Support
@Python_Codes
#Basics

zip() function

When we need to join many iterator objects like lists to get a single list we can use the zip function. The result shows each item to be grouped with their respective items from the other lists.

Example:

Year = (1999, 2003, 2011, 2017)
Month = ("Mar", "Jun", "Jan", "Dec")
Day = (11,21,13,5)
print zip(Year,Month,Day)

Output:
[(1999, 'Mar', 11), (2003, 'Jun', 21), (2011, 'Jan', 13), (2017, 'Dec', 5)]

Share and Support
@Python_Codes
#Basics

Transpose a Matrix

Transposing a matrix involves converting columns into rows. In python we can achieve it by designing some loop structure to iterate through the elements in the matrix and change their places or we can use the following script involving zip function in conjunction with the * operator to unzip a list which becomes a transpose of the given matrix.

Example:

x = [[31,17],
[40 ,51],
[13 ,12]]
print (zip(*x))

Output:
[(31, 40, 13), (17, 51, 12)]

Share and Support
@Python_Codes
#Basics

The _ Operator

The _ operator might be something that you might not have heard of. Here _ is the output of the last executed expression. Let’s check how it works.


Example:

>>> 2+ 3
5
>>> _ # the _ operator, it will return the output of the last executed statement.
>>> 5

Share and Support
@Python_Codes
#Basics

Swap keys and values of a dictionary

dictionary = {"a": 1, "b": 2, "c": 3}

reversed_dictionary = {j: i for i, j in dictionary.items()}

print(reversed)


Output:
{1: 'a', 2: 'b', 3: 'c'}

Share and Support
@Python_Codes
#Basics

Condition inside the print function

def is_positive(number):
print("Positive" if number > 0 else "Negative")



is_positive(-3)

Output:

Negative

Share and Support
@Python_Codes
#Basics

Convert a value into a complex number

print(complex(10, 2)) 

Output:
(10+2j)

Share and Support
@Python_Codes