5 Powerful Python One-Liners

Swap variable values

a, b = b, a

This one-liner allows you to swap the values of two variables 'a' and 'b' without needing a temporary variable. It takes advantage of Python's simultaneous assignment feature.

Find the maximum or minimum value in a list

max_value = max(my_list)  min_value = min(my_list)

These one-liners use the max() and min() functions to find the maximum and minimum values, respectively, in a given list my_list.

Count occurrences of an item in a list

count = my_list.count(item)

This one-liner uses the count() method to count the occurrences of a specific item in a list my_list.

Flatten a nested list

flattened_list = [item for sublist in nested_list for item in sublist]

This one-liner uses a nested list comprehension to flatten a list of lists (nested_list) into a single flat list (flattened_list).

Remove duplicates from a list while preserving the order

unique_list = list(dict.fromkeys(my_list))

This one-liner uses a dictionary (dict.fromkeys()) to remove duplicates from a list my_list. It converts the keys of the dictionary back to a list to preserve the order of the unique elements.

These programs cover basic concepts like input/output, arithmetic operations, conditional statements, loops, and using libraries. They provide a good starting point for beginners to practice and understand Python programming.

Thank you