How To Sort A Set Of Values?

Summary: This blog explores the steps to sort elements of a Set. Python offers the built-in sorted() function to sort elements in container objects such as a set or a list. For example: sorted({1, 5, 2}) sorts the elements in the set and returns the sorted list [1, 2, 5]. Note: All the solutions provided … Read more

A Simple Introduction to Set Comprehension in Python

Being hated by newbies, experienced Python coders can’t live without this awesome Python feature. In this article, I give you everything you need to know about set comprehensions using the bracket notation {}. What is Set Comprehension? Set comprehension is a concise way of creating sets in Python using the curly braces notation {expression for … Read more

How to Check If a Python List is Empty?

Believe it or not—how you answer this question in your day-to-day code reveals your true Python skill level to every master coder who reads your code. Beginner coders check if a list a is empty using crude statements like len(a)==0 or a==[]. While those solve the problem—they check if a list is empty—they are not … Read more

How to Loop Through a Python List in Pairs, Sliding Windows, and Batches?

Method 1: Iterating over Consecutive (Sliding) Windows Given are: Python list lst Window size n Problem Formulation: How to loop through the list in consecutive element-windows of size n, so that in each iteration, you can access the n next elements in the list? # INPUT: lst = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’] … Read more

How To Fix TypeError: List Indices Must Be Integers Or Slices, Not β€˜Str’?

✯ Overview Problem: Fixing TypeError: list indices must be integers or slices, not str in Python. Example: The following code lists a certain number of transactions entered by the user. Output: Solution: Please go through this solution only after you have gone through the scenarios mentioned below. Bugs like these can be really frustrating! ? But, … Read more

Python iter() — A Simple Illustrated Guide with Video

Python’s built-in iter() function returns an iterator for the given object. For example, iter([1, 2, 3]) creates an iterator for the list [1, 2, 3]. You can then iterate over all elements in the iterator, one element at a time, in a for or while loop such as: for x in iter([1, 2, 3]). Basic … Read more