How to Return a List in Python

Returning a list in Python is as simple as using the return statement from within a function, followed by an object of type list. For example: return [1, 2, 3]. This will return a list containing elements 1, 2, and 3. Return a list directly Returning a list in Python can be done by simply … Read more

TypeError: ‘int’ object is not iterable

This error occurs when you try to iterate over an integer in Python. To fix this, make sure anything after the in operator in Python is an iterable, such as a list. If you’re trying to use the integer to determine the number of times you’d like a for loop to run, use the range() … Read more

How to Write a Python for Loop on One Line

In Python, semicolons (;) can be used to join two separate lines on a single line, and for loops can have the body of the loop on the same line after the colon (:). Alternatively, you can use list comprehension to put a for loop on a single line. Simply put it on one line … Read more

How to Copy a List of Lists in Python

To copy a list of lists in Python, or a list containing any other complex types, use the deepcopy function in the copy module. Example: import copy; list2 = copy.deepcopy(list1). Can I just use list.copy? It might be tempting to just use the built-in .copy() method for a Python list to make a copy of … Read more

How to Print an Exception in Python

To print an exception in Python, you can either just call print(e) directly on the exception object, or use traceback.print_exc() to print the entire stack trace. You’ll have to import the traceback module to use the second option, though. How to print just the exception message Printing exceptions is easy in Python. Since they all … Read more

How to check if a string doesn’t contain a substring in Python

To check if a string doesn’t contain a substring in Python, just use the in operator. For example: “foo” not in “Hello world” will return True, i.e., the string “foo” isn’t found in the string “Hello world”. Alternatively, you can use the re library or the .rfind() method of Python’s built-in string class to do … Read more

[Solved] TypeError: str returned non-string (type NoneType)

The Python error “TypeError: str returned non-string (type NoneType)” means you aren’t returning a string from your class’ __str__ method. To fix this, make sure you’re actually returning a string. Python has methods called “dunder” methods, which is shorthand for “double underscore”. They are special methods you can add to your classes to do things … Read more