Pre-allocating a list of known sizes and assigning specific values to that list speeds up and improves efficiency. None is the most common placeholder in pre-allocation, and it is Python’s way of representing null or nothing.
Sometimes, you need slots ready to accept elements in your lists anytime. There is no better way to create slots using None, and that’s why you need to learn how to append a None in the list.
The most efficient way to add None is by using the append() method at the end of the list. It is a straightforward and concise approach, providing in-place modification.
main_list = [] main_list.append(None) print(main_list) # Output: [None]
One of the major drawbacks of the append() method is that you can only append one element at a time. To append multiple, you must use a for loop, which might not be the best case in each scenario.
Before adding, the list was empty. After adding None, now the list is not empty.
To append multiple Nones efficiently, you can use the extend() method with a multiply operator (*).
main_list = [] num_nones = 5 main_list.extend([None] * num_nones) print(main_list) # Output: [None, None, None, None, None]
Alternate approaches
Using index()
If you have an existing list with elements, and you want to insert None at a specific position, you can use the “index()” method.
main_list = [18, 19, 21] main_list.insert(2, None) print(main_list) # Output: [18, 19, None, 21]
In the above code, you can see that we added None at the 2nd index, which is after 19. You can add at the start or at the end of the list. It provides that flexibility.
Using concatenation
By definition, you can concatenate one list with another. Start with your existing list as the first list, then concatenate another list containing None values. When you concatenate both lists, the final list will contain Nones.
main_list = [18, 19, 21] none_list = [None, None, None] new_list = main_list + none_list print(new_list) # Output:[18, 19, 21, None, None, None]
You can see that the output list has 3 Nones at the end.
That’s all!