Write a python program to append items from a specified list.

Python: Append items from a specified list

Last update on January 02 2021 11:02:23 (UTC/GMT +8 hours)

(Python Example for Citizen Data Scientist & Business Analyst)

Write a Python program to append items from a specified list.

Sample Solution:

Python Code :

from array import * num_list = [1, 2, 6, -8] array_num = array('i', []) print("Items in the list: " + str(num_list)) print("Append items from the list: ") array_num.fromlist(num_list) print("Items in the array: "+str(array_num))

Sample Output:

Items in the list: [1, 2, 6, -8] Append items from the list: Items in the array: array('i', [1, 2, 6, -8])

Free Machine Learning & Data Science Coding Tutorials in Python & R for Beginners. Subscribe @ Western Australian Center for Applied Machine Learning & Data Science.


Western Australian Center for Applied Machine Learning & Data Science – Membership

Python List append()

In this tutorial, we will learn about the Python list append() method with the help of examples.

The append() method adds an item to the end of the list.

Example

currencies = ['Dollar', 'Euro', 'Pound']
# append 'Yen' to the list currencies.append('Yen')
print(currencies)
# Output: ['Dollar', 'Euro', 'Pound', 'Yen']

Python's .append(): Add Items to Your Lists in Place

by Leodanis Pozo Ramos basics python
Mark as Completed
Tweet Share Email

Table of Contents

Remove ads

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Building Lists With Python's .append()

Adding items to a list is a fairly common task in Python, so the language provides a bunch of methods and operators that can help you out with this operation. One of those methods is .append(). With .append(), you can add items to the end of an existing list object. You can also use .append() in a for loop to populate lists programmatically.

In this tutorial, you’ll learn how to:

  • Work with .append()
  • Populate lists using .append() and a for loop
  • Replace .append() with list comprehensions
  • Work with .append() in array.array() and collections.deque()

You’ll also code some examples of how to use .append() in practice. With this knowledge, you’ll be able to effectively use .append() in your programs.

Free Download: Get a sample chapter from Python Basics: A Practical Introduction to Python 3 to see how you can go from beginner to intermediate in Python with a complete curriculum, up-to-date for Python 3.8.

Python program to append an item to a list using extend method

The list extend method adds any iterable such as list, tuple, string, etc to the end of the existing list.

list.extend(iterator)

countries = ["India", "USA", "UK", "Italy"] print("List Before Appending Item") print(countries) tuple1 = ("Japan", "China", "France") countries.extend(tuple1) print("\nList After Appending Tuple using extend") print(countries) list1 = [19, 17, 39, 55] countries.extend(list1) print("\nList After Appending List sing extend") print(countries) countries.extend((11.5, 19.2)) print("\nList After Appending 11.5, 19.2 using extend") print(countries)List Before Appending Item ['India', 'USA', 'UK', 'Italy'] List After Appending Tuple using extend ['India', 'USA', 'UK', 'Italy', 'Japan', 'China', 'France'] List After Appending List sing extend ['India', 'USA', 'UK', 'Italy', 'Japan', 'China', 'France', 19, 17, 39, 55] List After Appending 11.5, 19.2 using extend ['India', 'USA', 'UK', 'Italy', 'Japan', 'China', 'France', 19, 17, 39, 55, 11.5, 19.2]

What are lists in Python? A definition for beginners

An array in programming is an ordered collection of items, and all items need to be of the same data type.

However, unlike other programming languages, arrays aren't a built-in data structure in Python. Instead of traditional arrays, Python uses lists.

Lists are essentially dynamic arrays and are one of the most common and powerful data structures in Python.

You can think of them as ordered containers. They store and organize similar kind of related data together.

The elements stored in a list can be of any data type.

There can be lists of integers (whole numbers), lists of floats (floating point numbers), lists of strings (text), and lists of any other built-in Python data type.

Although it is possible for lists to hold items of only the same data type, they are more flexible than traditional arrays. This means that there can be a variety of different data types inside the same list.

Lists have 0 or more items, meaning there can also be empty lists. Inside a list there can also be duplicate values.

Values are separated by a comma and enclosed in square brackets, [].

How to create lists in Python

To create a new list, first give the list a name. Then add the assignment operator(=) and a pair of opening and closing square brackets. Inside the brackets add the values you want the list to contain.

#create a new list of names names = ["Jimmy", "Timmy", "Kenny", "Lenny"] #print the list to the console print(names) #output #['Jimmy', 'Timmy', 'Kenny', 'Lenny']

How lists are indexed in Python

Lists maintain an order for each item.

Each item in the collection has an its own index number, which you can use to access the item itself.

Indexes in Python (and every other modern programming language) start at 0 and increase for every item in the list.

For example, the list created earlier on had 4 values:

names = ["Jimmy", "Timmy", "Kenny", "Lenny"]

The first value in the list, "Jimmy", has an index of 0.

The second value in the list, "Timmy", has an index of 1.

The third value in the list, "Kenny", has an index of 2.

The fourth value in the list, "Lenny", has an index of 3.

To access an element in the list by its index number, first write the name of the list, then in square brackets write the integer of the element's index.

For example, if you wanted to access the element that has an index of 2, you'd do:

names = ["Jimmy", "Timmy", "Kenny", "Lenny"] print(names[2]) #output #Kenny

How to append element in the list

Python provides built-in methods to append or add elements to the list. We can also append a list into another list. These methods are given below.

  • append(elmt) - It appends the value at the end of the list.
  • insert(index, elmt) - It inserts the value at the specified index position.
  • extends(iterable) - It extends the list by adding the iterable object.

Let's understand these methods by the following example.

1. append(elmt)

This function is used to add the element at the end of the list. The example is given below.

Example -

Output:

Current names List is: ['Joseph', 'Peter', 'Cook', 'Tim'] Please enter a name: Devansh Updated name List is: ['Joseph', 'Peter', 'Cook', 'Tim', 'Devansh']

2. insert(index, elmt)

The insert() function adds the elements at the given an index position. It is beneficial when we want to insert element at a specific position. The example is given below.

Example -

Output:

Current Numbers List: [10, 20, 30, 40, 50] The new list is: [10, 20, 30, 77, 40, 50] enter a number to add to list: 45 enter the index to add the number: 1 Updated Numbers List: [10, 45, 20, 30, 77, 40, 50]

3. extend(iterable)

The extends() function is used to add the iterable elements to the list. It accepts iterable object as an argument. Below is the example of adding iterable element.

Example -

Output:

[10, 20, 30, '52.10', '43.12'] [10, 20, 30, '52.10', '43.12', 40, 30] [10, 20, 30, '52.10', '43.12', 40, 30, 'A', 'p', 'p', 'l', 'e']

Next TopicHow to compare two lists in Python


← prev next →


Python - Add List Items

❮ Previous Next ❯

Append Items

To add an item to the end of the list, use the append() method:

Example

Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Try it Yourself »

Python List Refresher

Python lists can store zero or more items of a specific data type, such as strings, JSON objects, or numbers. For example, you can use a list to store a list of names or addresses. Lists are mutable. This means you can change their contents.

To create a new list in Python, you need to separate a list of values with commas and enclose it in square brackets []. Let’s create a list in Python, using this code:

toy_animals = ["Shark", "Dragon", "Bear", "Cat", "Giraffe"]

When we print out our list to the console, we can see the list that we’ve defined:

print(toy_animals)

Output:

["Shark", "Dragon", "Bear", "Cat", "Giraffe"]

Each item on our list has an index number, which can be used to reference an individual list item. These index numbers start with the value and increase for each item in a list. For our above toy_animals list, index numbers are assigned like this:

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

Find Your Bootcamp Match

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

Start your career switch today
» MORE: Python Map Function: A Step-By-Step Guide
“Shark”“Dragon”“Bear”“Cat”“Giraffe”
1234

The first item on our list Shark has the value 0. The last item Giraffe has the value 4. We can use these index numbers to access and manipulate our list. So, if we want to access the element with the index number 1, we can use the following code:

print(toy_animals[1])

Output:

"Dragon"

Lists are mutable, which means that you can add and remove items to an existing list. Now that we’ve explored the basics of lists and list indexing in Python, we can start using the append() and insert() methods.