How to Count the Number of Unique Values in a List in Python?

Problem Statement: Consider that you have been given a list in Python. How will you count the number of unique values in the list? Example: Let’s visualize the problem with the help of an example: Given: li = [‘a’, ‘a’, ‘b’, ‘c’, ‘b’, ‘d’, ‘d’, ‘a’]Output: The unique values in the given list are ‘a’, ‘b’, ‘c’, ‘d’. … Read more

How to Retrieve a Single Element from a Python Generator

This article will show you how to retrieve a single generator element in Python. Before moving forward, let’s review what a generator does. Quick Recap Generators 💡 Definition Generator: A generator is commonly used when processing vast amounts of data. This function uses minimal memory and produces results in less time than a standard function. … Read more

Python – List of Lists to List of Strings. How?

Coding Challenge 💬 Coding Challenge: Given a nested Python list, i.e., a list of lists. How to convert it to a string list, so that each inner list becomes a single string? Consider the following examples: 1. Input: [[‘h’, ‘e’, ‘l’, ‘l’, ‘o’], [‘w’, ‘o’, ‘r’, ‘l’, ‘d’]] Output: [‘hello’, ‘world’] 2. Input: [[‘h’, ‘i’], … Read more

HOW TO CHECK YOUR PYTHON VERSION

To check your Python version, run python ‐‐version in your command line (Windows), shell (Mac), or terminal (Linux/Ubuntu). To check your Python version in your script, run import sys to get the module and use sys.version to find detailed version information in your code. Let’s get a quick overview of the different ways to check … Read more

If-Then-Else in One Line Python

Quick answer: How to put a simple if-then-else statement in one line of Python code? To put an if-then-else statement in one line, use Python’s ternary operator x if c else y. This returns the result of expression x if the Boolean condition c evaluates to True. Otherwise, the ternary operator returns the alternative expression … Read more

Python One Line Ternary

The most basic ternary operator x if c else y consists of three operands x, c, and y. It is an expression with a return value. The ternary operator returns x if the Boolean expression c evaluates to True. Otherwise, if the expression c evaluates to False, the ternary operator returns the alternative y. Ternary … Read more

How to Reverse a Range in Python?

Summary: Use negative step in the range() function to reverse the given sequnce as: range(start, stop, -step). Another workaround is to apply the reversed() function to the given range to reverse it as: reversed(range(start, stop)). Problem: Given a range/sequence of numbers, how will you reverse the range? Example: Given:# Given rangefor i in range(1, 6): … Read more