USEFUL PYTHON TIPS AND TRICKS
馃憖 I'd like to share this today!!!
# Swap two variables with one line of code. Shorten your code
a = 1
b =2
a, b = b, a
# Duplicate strings without looping
fruit_names = "Banana", "Mango"
print (fruit_names * 4)
# Reverse a string
my_words = "The Quick Brown Fox"
reverse_words = my_words[::-1]
print(reverse_words)
# Compress a list of strings into one string
my_words = ["This", "is", "a", "Test"]
combine_all = " ".join(my_words)
print(combine_all)
# You can also compare or evaluate in a line of code
x = 100
res = 0 < x < 1000 > 50
print(res)
# Find the most frequest element in a list
test_list = [4, 3, 2, 3, 2, 4, 3, 6, 9, 41, 2, 3, 4]
most_frequent = max(set(test_list), key = test_list.count)
print(most_frequent)
# Unpack list to separate variables (or assign list to separate varabiels)
arr_list = [1,2,3]
a,b,c = arr_list
print(a,b,c)
# One-liner if-else statements (can be combined with user input!)
my_age = 30
age_group = "Adult" if my_age > 18 else "Child"
print(age_group)
# Loop through a list with one line of code
numbers_list = [1,2,3,4,5]
squared_numbers = [num * num for num in numbers_list]
print(squared_numbers)
# Using dictionary comprehension to raise the value of a dictionary to a
# second power
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
squared_dict = {key: num * num for (key, num) in my_dict.items()}
print(squared_dict)
# Simpler If statements
# The original will be something like:
#if n == 0 or n == 1 or n == 2 or n == 3 or n ==4 or n == 5:
# But you can do this instead
n = 10
if n in[0,1,2,4,4,5]:
print("It is the number I was looking for...")
else:
print("This is not the number")
///""""""""""""//////////
Comments
Post a Comment