Python Snippets Flashcards
(57 cards)
Python Snippet
Explanation
if not nums:
Check if the list is empty.
if x in my_set:
Check if ‘x’ is an element in the set.
for i, val in enumerate(arr):
Loop with both index and value.
nums = [x for x in arr if x % 2 == 0]
List of even numbers from ‘arr’.
return sorted(arr)
Return a new sorted list.
arr.sort()
Sort the list in-place.
from collections import Counter
Import Counter to count elements.
Counter(arr)
Create frequency dictionary of ‘arr’.
’‘.join(chars)
Join list of characters into a string.
list(map(int, input().split()))
Read integers from input.
while stack:
Loop while stack is not empty.
stack.append(x)
Push ‘x’ onto the stack.
stack.pop()
Pop the top element from the stack.
if not stack:
Check if stack is empty.
set1 & set2
Intersection of two sets.
set1 | set2
Union of two sets.
set1 - set2
Elements in set1 but not in set2.
nums[::-1]
Reverse a list.
s[::-1]
Reverse a string.
any(x > 10 for x in arr)
Check if any element is > 10.
all(x > 0 for x in arr)
Check if all elements are > 0.
{i: 0 for i in range(5)}
Create a dictionary with values 0.
for key in my_dict:
Loop through dictionary keys.