How to Extend a List in Python 


               


How to Extend a List in Python



Python


In this article, we show how to extend a list in Python.

Extending a list means adding more elements to an existing list.

To extend a list in Python, we use the extend() function in Python.

Another way to add items to a list in Python is by using the append() function. However, the append() function only allows you to add one item at a time. The extend() function can add multiple items to a list all in one statement.

In our code below, we create a variable, list1, which contains a list of integers. This list is composed of 4 values. To this list, we then add an additional 3 integers with the extend() function.

So the first thing we do is we create a variable, list1, which we set equal to [1,2,3,4]

After we create this variable, we extend it using the extend() function.

To this list1 variable, we adds the numbers 35 and 72.

Know that the extend() function is taking in a new list of numbers. So the extend after the extend keyword is a list (brackets) within parentheses.

Now when we call the list1 object, we see the new appended items at the end of the list.

The list now contains 6 items.

So this is how to extend a list in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...