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.
One of the most common ways to add an integer to a list, let alone any other type of data, is to use the
1, 2, 3] int_list.append(4) int_list [1, 2, 3, 4]int_list = [
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.
If you need to add multiple integers to a list, you can use the
extend() method, which concatenates one list to another.
1, 2, 3] int_list.extend([4, 5, 6]) int_list [1, 2, 3, 4, 5, 6]int_list = [
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.
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.
1, 2, 4] int_list.insert(2, 3) int_list [1, 2, 3, 4]int_list = [
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.
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
1, 2, 3] int_list = int_list + [4, 5, 6] int_list [1, 2, 3, 4, 5, 6]int_list = [
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.
Building Your First Convolutional Neural Network With Keras# python# artificial intelligence# machine learning# tensorflow
Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...