Python | Add list at beginning of list

Python | Add list at beginning of list

Appending one list to another is a common operation in Python. If you want to add (or append) one list to the beginning of another list, there are several ways to do this.

1. Using + operator:

You can simply concatenate two lists using the + operator.

def add_list_at_beginning(original_list, list_to_add): return list_to_add + original_list original = [4, 5, 6] to_add = [1, 2, 3] print(add_list_at_beginning(original, to_add)) # Expected: [1, 2, 3, 4, 5, 6] 

2. Using list slicing:

This method involves modifying the original list in place.

def add_list_at_beginning_inplace(original_list, list_to_add): original_list[:0] = list_to_add original = [4, 5, 6] to_add = [1, 2, 3] add_list_at_beginning_inplace(original, to_add) print(original) # Expected: [1, 2, 3, 4, 5, 6] 

3. Using extend() method:

This also modifies the original list in place. First, we reverse the order of the lists and then use extend(). This is a bit more roundabout but showcases the use of extend() for such tasks.

def add_list_at_beginning_extend(original_list, list_to_add): list_to_add.extend(original_list) original_list.clear() original_list.extend(list_to_add) original = [4, 5, 6] to_add = [1, 2, 3] add_list_at_beginning_extend(original, to_add) print(original) # Expected: [1, 2, 3, 4, 5, 6] 

4. Using list unpacking (Python 3.5+):

In Python 3.5 and newer, you can use the unpacking feature (*) to append lists.

def add_list_at_beginning_unpacking(original_list, list_to_add): return [*list_to_add, *original_list] original = [4, 5, 6] to_add = [1, 2, 3] print(add_list_at_beginning_unpacking(original, to_add)) # Expected: [1, 2, 3, 4, 5, 6] 

Any of these methods can be employed based on the specific needs of the application or based on personal coding preferences.


More Tags

url bitset letters each react-leaflet jquery-ui-datepicker visual-studio-2010 uisearchbardisplaycontrol apdu coreclr

More Programming Guides

Other Guides

More Programming Examples