Add Integers to a List in Python

# Add Integers to a List in Python

In Python, you can add integers to a list using a variety of methods, a few of which we'll take a look at here.

### Append

One of the most common ways to add an integer to a list, let alone any other type of data, is to use the append() method.

>>> int_list = [1, 2, 3]
>>> int_list.append(4)
>>> int_list
[1, 2, 3, 4]


This will simply add a single integer to the very end of the list. There are a number of other ways to add one or more integers to a list, which we'll explore in the next sections.

### Extend

If you need to add multiple integers to a list, you can use the extend() method, which concatenates one list to another.

>>> int_list = [1, 2, 3]
>>> int_list.extend([4, 5, 6])
>>> int_list
[1, 2, 3, 4, 5, 6]


## Get free courses, guided projects, and more

Here you can see that the second list, [4, 5, 6], was added to the end of the first list, [1, 2, 3], resulting in one long list. This is the preferred method if you have more than one integer to add to your list.

### Insert

You might not always want to add an integer to the end of the list, but instead you might want to add it to a specific spot in the list using an index. The insert() method allows you to do this.

>>> int_list = [1, 2, 4]
>>> int_list.insert(2, 3)
>>> int_list
[1, 2, 3, 4]


Here we added the integer 3 to the list at index 2. You could use this method to add an integer at any point in the list, including at the beginning. This is especially helpful for when you don't know beforehand where the integer will go in the list and is computed at runtime.

### Combining Lists

While the extend() method is typically the preferred way to combine two lists, there is another way to combine two lists. This is called a concatenation and is done using the + operator.

>>> int_list = [1, 2, 3]
>>> int_list = int_list + [4, 5, 6]
>>> int_list
[1, 2, 3, 4, 5, 6]


Since the list object has overloaded the + operator, you can use it to "add" two lists together. This can be done using a single integer, as well as a variable number of integers.

Last Updated: July 1st, 2022
Project

### Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
Details
Project

### Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

Details