0% found this document useful (0 votes)
20 views2 pages

Python Shortcuts Cheat Sheet

This document provides a cheat sheet of Python shortcuts with examples for various functionalities. It includes techniques such as ternary operations, list comprehension, dictionary comprehension, and lambda functions. Additionally, it covers methods for manipulating lists, such as zipping, sorting, and unpacking.

Uploaded by

janhavitidke14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views2 pages

Python Shortcuts Cheat Sheet

This document provides a cheat sheet of Python shortcuts with examples for various functionalities. It includes techniques such as ternary operations, list comprehension, dictionary comprehension, and lambda functions. Additionally, it covers methods for manipulating lists, such as zipping, sorting, and unpacking.

Uploaded by

janhavitidke14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Shortcuts Cheat Sheet (with Examples)

Ternary / One-Line If-Else


Example: status = "Adult" if age >= 18 else "Minor"

Swapping Variables Without Temp


Example: a, b = b, a

List Comprehension
Example: [x*x for x in range(5)]

List Comprehension with Condition


Example: [x for x in range(10) if x % 2 == 0]

Flatten a 2D List
Example: [num for row in matrix for num in row]

Dictionary Comprehension
Example: {x: x*x for x in range(5)}

Set Comprehension
Example: {x for x in [1,2,2,3,4,4]}

Enumerate with Index


Example: for i, fruit in enumerate(fruits):

Zip Two Lists Together


Example: for name, score in zip(names, scores):

Lambda Functions
Example: square = lambda x: x * x

Sort List of Tuples by Second Value


Example: sorted(items, key=lambda x: x[1])

Check if a List is Empty


Example: if not mylist:

Multiple Conditions in One Line


Example: if 5 < x < 15:

Get Max/Min with Key


Example: max(words, key=len)

Join List of Strings


Example: " ".join(words)

List All Even Numbers


Example: list(range(0, 20, 2))
Unpack List into Variables
Example: a, b, c = [1, 2, 3]

*args and **kwargs


Example: def greet(*names, **details):

You might also like