10 Useful Python Code Snippets

Here are 10 useful Python code snippets that you can use as building blocks in your own projects:

Swap two variables:

a, b = b, a

Remove duplicates from a list:

unique_list = list(set(original_list))

Check if an item is in a list:

if item in list:
    # do something

Concatenate strings:

sentence = " ".join(words)

Check if a string starts with a certain substring:

if string.startswith(substring):
    # do something

Get 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