How To Add An Empty Element To A List In Python

To insert or append an empty element into a Python list you need to first define what is meant by the word empty. By empty do you mean an empty string, None or something else? While I may use None in this post you can easily substitute it for something else according to your requirements. To add an empty element into a list either replace the existing element with the empty variable or if inserting it at the end use the list method .append() or if inserting it at a specific place use the other list method .insert(). ...

December 1, 2021 · 4 min · 768 words · Ryan Sheehy

How To Check If List Is Empty In Python

Similar to the previous post on how to check if a string is empty the same principles and methods apply when checking if a list is empty in Python. To check if a list is empty either use the direct approach by using an expression where a list is compared to an empty list or use the boolean expression with a not operator (i.e. if not my_empty_list:) or use the built-in function len() to see if the length of the list is 0. ...

November 26, 2021 · 10 min · 1919 words · Ryan Sheehy

Python: Sort List From Second (or Nth Index) On

How do you sort a list by the second (or nth) element on in Python? How can you leave the first or nth elements in a list as they are but then have the remaining elements in the list sorted? When applying the .sort() list method on a list Python will sort all elements in that list, but what if you only wanted to sort after a certain index number? ...

July 6, 2021 · 6 min · 1239 words · Ryan Sheehy

List Changes Unexpectedly In Python: How Can You Stop It?

Why is it when you copy a list in Python doing b_list = a_list that, any changes made to a_list or to b_list modify the other list? If you’ve played with lists in Python you will reach a point where you want to copy a list to make modifications to it without changing the original list. Initially you would think the following would work: 1 2 3 4 5 6 7 >>> a_list = [1, 2, 3] >>> b_list = a_list >>> b_list.append(4) >>> print(b_list) [1, 2, 3, 4] >>> print(a_list) [1, 2, 3, 4] As you can see from the above example even though b_list was the only list which had an extra element added to it, a_list also changed! ...

9 min · 1739 words · Ryan Sheehy