Python tips

Remove duplicates in a list

list1 = ['a', 'a', 'b', 'c', 'c', 'd', 'e', 'e', 'e', 'f', 'g']

list2 = [1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 7]

print(set(list1))
print(set(list2))

Output

{'g', 'c', 'a', 'e', 'd', 'b', 'f'}
{1, 2, 3, 4, 5, 6, 7}

Chaining of comparison operators

n = 77

# chaining of same operator(<)
result = 7 < n < 777
print(result)

# chaining of mixed operators
result = 70 > n <=84
print(result)

Output

True
False

Swapping of two numbers

x, y = 50, 100
x, y = y, x

print(x, y)

Output

100 50

Create dictionary from two related sequences

# dictionary from two related lists

list1 = ('x', 'y', 'z')
list2 = (100, 200, 300)

print(dict(zip(list1, list2)))

Output

{'x': 100, 'y': 200, 'z': 300}

Print any string N times

# print string N times

N = 3
string = 'Code'
print(string * N)

Output

CodeCodeCode

Check the memory usage of an object

# Memory usage of an object

import sys

x = 777
print(sys.getsizeof(x))

Output

28

Return multiple values from functions

# Return multiple values from function

def multipleValue():
    return 1, 2 , 3 , 4

x, y, z, a = multipleValue()
print(x, y, z, a)

Output

1 2 3 4

Creating a single string from all the elements in list

str_list = ['I', 'love', 'Programming']

print(" ".join(str_list))

Output

I love Programming

Reversing a string

# Reversing a string

string = 'CodeFires'
print(string[::-1])

Output

seriFedoC

Swapping Variables

When you need to swap two variables, the most common way is to use a third, temporary variable. However, Python allows you to swap variables in just one line of code using tuples and packing/unpacking:

# Swapping variables)
a = "January"
b = "2019"
print(a, b)
a, b = b, a
print(b, a)

January 2019
January 2019