51
loading...
This website collects cookies to deliver better user experience
# Instead of this
x = 10
y = 10
z = 10
# Use this
x = y = z = 10
x, y = [1, 2]
# x = 1, y = 2
x, *y = [1, 2, 3, 4, 5]
# x = 1, y = [2, 3, 4, 5]
x, *y, z = [1, 2, 3, 4, 5]
# x = 1, y = [2, 3, 4], z = 5
# Instead of this
temp = x
x = y
y = temp
# Use this
x, y = y, x
snake_case
is preferred over camelCase
for variables and functions names.# Instead of this
def isEven(num):
pass
# Use this
def is_even(num):
pass
# Instead of this
def is_even(num):
if num % 2 == 0:
print("Even")
else:
print("Odd")
# Use this
def is_even(num):
print("Even") if num % 2 == 0 else print("Odd")
# Or this
def is_even(num):
print("Even" if num % 2 == 0 else "Odd")
name = "Dobby"
item = "Socks"
# Instead of this
print("%s likes %s." %(name, item))
# Or this
print("{} likes {}.".format(name, item))
# Use this
print(f"{name} likes {item}.")
# Instead of this
if 99 < x and x < 1000:
print("x is a 3 digit number")
# Use this
if 99 < x < 1000:
print("x is a 3 digit number")
numbers = [1, 2, 3, 4, 5, 6]
# Instead of this
for i in range(len(numbers)):
print(numbers[i])
# Use this
for number in numbers:
print(number)
# Both of these yields the same output
enumerate()
.names = ['Harry', 'Ron', 'Hermione', 'Ginny', 'Neville']
for index, value in enumerate(names):
print(index, value)
# Instead of this
l = ['a', 'e', 'i', 'o', 'u']
def is_vowel(char):
if char in l:
print("Vowel")
# Use this
s = {'a', 'e', 'i', 'o', 'u'}
def is_vowel(char):
if char in s:
print("Vowel")
arr = [1, 2, 3, 4, 5, 6]
res = []
# Instead of this
for num in arr:
if num % 2 == 0:
res.append(num * 2)
else:
res.append(num)
# Use this
res = [(num * 2 if num % 2 == 0 else num) for num in arr]
dict.items()
to iterate through a dictionary.roll_name = {
315: "Dharan",
705: "Priya",
403: "Aghil"
}
# Instead of this
for key in roll_name:
print(key, roll_name[key])
# Do this
for key, value in roll_name.items():
print(key, value)