Python dir() — A Simple Guide with Video

If used without argument, Python’s built-in dir() function returns the function and variable names defined in the local scope—the namespace of your current module. If used with an object argument, dir(object) returns a list of attribute and method names defined in the object’s scope. Thus, dir() returns all names in a given scope. Usage Learn … Read more

Python dict() — A Simple Guide with Video

Python’s built-in dict() function creates and returns a new dictionary object from the comma-separated argument list of key = value mappings. For example, dict(name = ‘Alice’, age = 22, profession = ‘programmer’) creates a dictionary with three mappings: {‘name’: ‘Alice’, ‘age’: 22, ‘profession’: ‘programmer’}. A dictionary is an unordered and mutable data structure, so it … Read more

How To Sort A Dictionary By Value in Python?

Summary: Use one of the following methods to sort a dictionary by value: Using The sorted(dict1, key=dict1.get) Method. Using Dictionary Comprehension And Lambda With sorted() Method. Using OrderedDict (For Older Versions Of Python). Using itemgetter() with sorted() Method. Using Counter subclass. Problem: Given a dictionary; how to sort it by values? Example: The following example … Read more

Python Double Asterisk (**)

Summary: The double asterisk operator has the following uses: a**b – Exponentiation. def f(**kwargs) – Unpacking: Defining an arbitrary number of keyword arguments. f(**d) – Dictionary Unpacking. f(**d1,**d2) – Merging Dictionaries. While using a function in your program, you might be uncertain about the number of named arguments that have to be passed into the … Read more

How To Pass a Variable By Reference In Python?

Summary: Variables are passed by object reference in Python. Therefore, mutable objects are passed by reference while immutable objects are passed by value in Python. To pass immutable objects by reference you can return and reassign the value to the variable, or pass it inside a dictionary/list, or create a class and use the self … Read more

How to Remove Duplicates From a Python List While Preserving Order?

To remove duplicates from a Python list while preserving the order of the elements, use the code list(dict.fromkeys(list)) that goes through two phases: (1) Convert the list to a dict using the dict.fromkeys() function with the list elements as keys and None as dict values. (2) Convert the dictionary back to a list using the … Read more

How To Format A String That Contains Curly Braces In Python?

Summary: Use one of the following methods to format strings that contain curly braces: Use double curly braces {{}} Use the old string formatting, i.e. the % operator Use the JSON Library Use Template Strings Problem: Given a string literal with curly braces; how to format the string and ensure that the curly braces are … Read more

56 Python One-Liners to Impress Your Friends

This is a running document in which I’ll answer all questions regarding the single line of Python code. It’s based on my interactive collection here but without the slow videos and embedded code shells. Let’s get started! Python One Line If Else You can use a simple if statement in a single line of code. … Read more

Python One Line Dictionary

Python’s dictionary data structure is one of the most powerful, most underutilized data structures in Python. Why? Because checking membership is more efficient for dictionaries than for lists, while accessing elements is easier for dictionaries than for sets. In this tutorial, you’ll learn how to perform four common dictionary operations in one line of Python … Read more

How to Solve Python “TypeError: β€˜int’ object is not iterable”?

It’s quite common for your code to throw a typeerror, especially if you’re just starting out with Python. The reason for this is that the interpreter expects variables of certain types in certain places in the code. We’ll look at a specific example of such an error: “typeerror: ‘int’ object is not iterable”. Exercise: Run … Read more

Replacements For Switch Statement In Python?

Summary: Since switch-case statements are not a part of Python, you can use one of the following methods to create a switch-case construct in your code : Using a Python Dictionary Creating a Custom Switch Class Using if-elif-else Conditional Statements Using a Lambda Function Problem: Given a selection control switch case scenario in Python; how … Read more

How To Resolve UnboundLocalError On Local Variable When Reassigned After The First Use?

Summary: To resolve an UnboundLocalError when the local variable is reassigned after the first use, you can either use the global keyword or the nonlocal keyword. The global keyword allows you to modify the values of a global variable from within a function’s local scope while the nonlocal keyword provides similar functionality in case of … Read more