Lists & loops
Iterate, transform, and combine sequences with readable loop patterns.
Find Duplicate Elements in a Python List
Identifies and returns duplicate elements from a Python list using sets for efficient membership tests.
def find_duplicates(lst):
seen = set()
duplicates = set()
for item in lst:
if item in seen:
duplicates.add(item)
else:
seen.add(item)
return list(duplicates)
if __name__ == "__main__":
sample = [1, 2, 3, 2, 4, 1, 5, 3]
print(find_duplicates(sample))
How to Get the Union of Two Lists Without Duplicates in Python
Merge two lists and remove duplicate values using a set, then convert back to a list.
def union_without_duplicates(list1, list2):
return list(set(list1 + list2))
if __name__ == "__main__":
list_a = [1, 2, 3, 4]
list_b = [3, 4, 5, 6]
result = union_without_duplicates(list_a, list_b)
print(f"Union of {list_a} and {list_b}: {result}")
How to Validate Text Against Forbidden Words in Python
Checks whether a given text contains any forbidden words and returns a tuple with validity and offending words.
def validate_text(text, forbidden_words):
"""
Checks that text does not contain any forbidden words.
Returns (is_valid, offending_words) tuple.
"""
words = text.lower().split()
found = [word for word in words if word in forbidden_words]
return len(found) == 0, found
if __name__ == "__main…
Intersection of Two Lists Preserving Order in Python
This code returns the common elements between two lists while preserving the order they appear in the first list, filtering out duplicates.
def intersection_preserving_order(list1, list2):
"""
Return the intersection of two lists while preserving the order
of elements as they appear in list1.
"""
set2 = set(list2)
result = []
seen = set()
for item in list1:
if item in set2 and item not in seen:
resu…
Symmetric difference between two lists in Python
Find elements present in exactly one of two lists, preserving original order, with a simple Python function.
def symmetric_difference(list1, list2):
"""
Return the symmetric difference of two lists.
Elements present in exactly one of the lists, preserving order.
"""
set1 = set(list1)
set2 = set(list2)
# Elements in list1 but not in list2
diff1 = [x for x in list1 if x not in set2]
# E…
Browse by section
Each section groups closely related Python snippets.
Lists & loops — Python code examples
What you will find here
This page collects lists & loops snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.