Here are 10 useful Python code snippets that you can use as building blocks in your own projects:
Swap two variables:
a, b = b, aRemove duplicates from a list:
unique_list = list(set(original_list))Check if an item is in a list:
if item in list:
# do somethingConcatenate strings:
sentence = " ".join(words)Check if a string starts with a certain substring:
if string.startswith(substring):
# do somethingGet the length of a string:
length = len(string)Split a string into a list:
words = string.split()Sort a list:
sorted_list = sorted(original_list)Reverse a list:
reversed_list = list(reversed(original_list))Get the sum of all elements in a list:
sum = sum(numbers)
Comments
Post a Comment