Cheatsheet

Contents

Cheatsheet#

This page containsPython Beginner’s Cheatsheet, a short list with some hidden Gems

👉 New toApp-Generator? Sign IN withGitHub orGenerate Web Apps in no time (free service).

String Operations You Might Not Know

# Remove whitespace from both endstext="  hello  "text.strip()# "hello"# Center text in a fixed width"Python".center(10,"*")# "**Python**"# Split string into fixed-width chunkschunks=[text[i:i+3]foriinrange(0,len(text),3)]

List Tricks

# Create a list of numbers easilynumbers=list(range(1,11))# [1, 2, 3, ..., 10]# Get last n itemsmy_list=[1,2,3,4,5]last_three=my_list[-3:]# [3, 4, 5]# Remove duplicates while maintaining ordermy_list=list(dict.fromkeys(my_list))

Dictionary Magic

# Get value with fallback if key doesn't existmy_dict={'a':1}value=my_dict.get('b','not found')# 'not found'# Merge dictionariesdict1={'a':1}dict2={'b':2}merged={**dict1,**dict2}# {'a': 1, 'b': 2}

Loop Enhancements

# Enumerate with custom start indexfori,iteminenumerate(['a','b','c'],start=1):print(f"{i}:{item}")# 1: a, 2: b, 3: c# Loop over multiple lists simultaneouslyforx,yinzip([1,2,3],['a','b','c']):print(f"{x}-{y}")# 1-a, 2-b, 3-c

File Operations

# Read file directly into a list of lineswithopen('file.txt')asf:lines=f.read().splitlines()# Write multiple lines at oncelines=['line1','line2','line3']withopen('file.txt','w')asf:f.write('\n'.join(lines))

Built-in Functions You Should Know

# Convert multiple inputs to integersx,y,z=map(int,input().split())# Find largest/smallest n itemsimportheapqnumbers=[10,5,8,3,1]largest_three=heapq.nlargest(3,numbers)# [10, 8, 5]

String Formatting

# f-strings with formattingname="Alice"age=25.5print(f"{name:>10}")# Right align with width 10print(f"{age:.1f}")# One decimal place# Format numbers with commasnumber=1000000print(f"{number:,}")# 1,000,000

Collection Operations

fromcollectionsimportCounter,defaultdict# Count occurrencestext="hello world"letter_count=Counter(text)# {'l': 3, 'o': 2, ...}# Dictionary with default valued=defaultdict(list)d['new_key'].append(1)# No KeyError if key doesn't exist

Conditional Assignments

# Ternary operatorx=5status="even"ifx%2==0else"odd"# Multiple conditionsgrade="A"ifscore>=90else"B"ifscore>=80else"C"

Error Handling

# Multiple exception typestry:# some codeexcept(TypeError,ValueError)ase:print(f"Error:{e}")# Else clause in try-excepttry:result=perform_operation()exceptException:print("Error occurred")else:print("Operation successful!")finally:print("Cleanup code")

Context Managers

# Custom context managerfromcontextlibimportcontextmanager@contextmanagerdeftimer():fromtimeimporttimestart=time()yieldprint(f"Elapsed:{time()-start:.2f} seconds")withtimer():# Your code herepass

PRO Tips

  • Usehelp() function to get documentation

  • Trydir() to see all attributes of an object

  • The interactive interpreter can be cleared with ctrl + l

  • Use_` to access the last printed expression in interactive mode

  • IPython’s ? and ?? for quick help and source code

Links#

Contents