Write a python program to create append and remove lists in python

To add and remove items from a list in Python; In this tutorial, you will learn how to add and remove items or elements from a list in python program.

Python has two methods first is append(), which is used to add an element in list. And the second method is pop, which is used to remove an element from list. Also, we will share these two methods by programs.

Python List append() Method

This method is used to add/append an object (which will be passed in method as parameter) to the list.

Syntax:

list.append(element)

Python Program to add elements in list

# Declaring a list with integer and string elements list = [10, 20, 30, "Bombay", "Pune"] # printing list print("List elements are: ", list) # adding elements list.append (40) list.append (50) list.append ("Kolkata") # printing list after adding elements print("List elements: ", list)

After executing the program, the output will be:

List elements are: [10, 20, 30, 'Bombay', 'Pune'] List elements: [10, 20, 30, 'Bombay', 'Pune', 40, 50, 'Kolkata']

Python List pop() Method

This method is used to remove/pop an object from the list.

Syntax:

list.pop()

Python Program to remove elements from list

# Declaring a list with integer and string elements list = [10, 20, 30, "Bombay", "Pune"] # printing list print("List elements are: ", list) # adding elements list.append (40) list.append (50) list.append ("Kolkata") # printing list after adding elements print("List elements: ", list) # removing elements list.pop(); # printing list print("List elements: ", list)

After executing the program, the output will be:

List elements are: [10, 20, 30, 'Bombay', 'Pune'] List elements: [10, 20, 30, 'Bombay', 'Pune', 40, 50, 'Kolkata'] List elements: [10, 20, 30, 'Bombay', 'Pune', 40, 50]

PythonServer Side ProgrammingProgramming

When it is required to append, delete, and display the elements of a list using classes, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to add elements to the list, delete elements from the list and display the elements of the list using objects.

Below is a demonstration for the same −

In this tutorial, we'll learn everything about Python lists: creating lists, changing list elements, removing elements, and other list operations with the help of examples.

In Python, a list is a data type, that stores a collection of different objects [items] within a square bracket[[]]. Each item in a list is separated by a comma[,] with the first item at index 0.

Note: Moving forward, all the examples in this tutorial will directly run from a Python shell, unless otherwise stated.

Below is an example of a list with 5 items.

>>> l = ['what','who','where','when','how'] >>>l ['what','who','where','when','how']

In the above example, we can see that the list has String objects as items, and each item is separated by a comma.

Characteristics Of Python List

Before we look at how we can manipulate items in a list, let’s look at some of the characteristics that make Python lists favored.

Python Lists Are Container Sequences

Unlike flat sequences[string, array.array, memoryview, etc] that can only hold items of one type, a list is a container sequence that can hold items of one type as well as of different types.

Example with items of one type

Let’s open our python shell and define a list of numbers.

>>> numbers = ['one','two','three','four','five'] >>> numbers ['one','two','three','four','five']

The example above shows a list of items of the same type, in this case of type string[str].

Example with items of different types

Let’s open our Python shell and define another version of a list of numbers.

>>> numbers = ['one',2,3,'four',5.0] >>> numbers ['one',2,3,'four',5.0]

The example above shows a list of items of different types. The types are string, integer, and float.

// a sketch showing the list of items and their types as annotation

The Python list can also hold all objects such as functions, classes, modules, lists, tuples, and much more.

Open an editor and paste the below code:

def test[]: """This is a function""" print["This is a test"] if __name__ == '__main__': print[test] # return instance object of function 'test' instance = type[test] print[instance] # create a list of colors colors = ["red","blue","green"] print[colors] # create a list holding all the various data types defined above, including boolean. my_list = [test, instance, colors, False] print[my_list]

Output

Python Lists Are Ordered Sequences

A Python list is an ordered collection of objects. The position of each item in a list is very important. In fact, two lists with the same items are not the same if the order in which the items are positioned is not the same.

>>> ['a','b','c','d'] == ['a','c','b','d'] False

This characteristic of the Python list makes it possible to access its items by index and slicing[more on this later].

Python Lists Are Mutable Sequences

Python lists are mutable. But what is a mutable object? It’s simply an object that can be modified after it is created. Examples of other mutable sequences are dictionary, array.array, collections.deque.

Why mutable? Sequences like lists are used for complex operations, so it makes sense that they should be able to change, grow, shrink, update, etc. This is only possible with mutability. Mutability also enables us to modify lists in place[more on this].

Let’s verify the mutability of a list with the example below.

Just open an editor and paste the code:

def veryfiy_mutability[]: # create a list l = [9,0,4,3,5] print["Display before modifying"] print["List: {}\nId: {}".format[l,id[l]]] # modify the list by replacing the item at # index 3 to the item -2. l[3] = -2 print["Display after modifying"] print["List: {}\nId: {}".format[l,id[l]]] if __name__ == '__main__': veryfiy_mutability[]

Output

From the above output, we notice that the list before and after modification is different. However, the Id value is the same. The Id value here represents the object’s address in memory – that is obtained with Python id[].

This tells us that, though the list content has changed, it is still the same object. Hence, this satisfies our definition: “It’s simply an object that can be modified after it is created

Note: In the example above, we used indexing[more on this] to modify the list.

Manipulating Python Lists

With Python lists, the sky’s our limit. There are countless things we can do with lists like adding, deleting, indexing, slicing, checking for membership, and much more. Also, Python has built-in functions that help to make manipulating lists more exciting.

In this section, we will be looking at some commonly used list operations.

To create a list, you simply put a number of items or expressions in a square bracket separated by commas.

[expression1, expression2,...,expresionN]>>> l = [4,3,5,9+3,False] >>> l [4, 3, 5, 12, False]

Also, Python has a built-in object called list[] that can be used to create lists.

list[ sequence ]>>> l = list[] # create an empty list >>> l []

Python list[] can take in sequence types and convert them into lists. This is the typical way of converting a tuple into a list.

>>> t = [4,3,5] # tuple >>>l = list[t] # convert into list [4,3,5]

In the example above, we used the data type Tuple. It is similar to a list but unlike lists, it is immutable and its items are enclosed in parentheses.

Another means by which we can create a list is by using list comprehensions that has the following syntax.

[expression for item in sequence]>>> [i**2 for i in range[4]] [0, 1, 4, 9]

It is worth noting that Python lists are passed by reference. Meaning, assigning a list will provide its memory location identity. The mistake that many newbies do is to create lists this way.

>>> l1 = l2 = [4,3] # wrong way to create separate list objects >>> l1 [4,3] >>> l2 [4,3]

Here, we might think that we have created two different lists, but truly we have just created one. Let’s demonstrate this by modifying one of the variables.

>>> l1[0] = 0 >>> l1 [0,3] >>> l2 [0,3]

We notice that modifying one variable changes the other. This is because both the variables l1 and l2 hold the same memory location identity, so they both point to the same object.

Adding Items To A List

Python has many ways to add elements to its list. The most common way is by using the append[] method. The other ways are by using the extend[] method. Indexing and slicing[more on these later] are more likely used to replace items in a list.

#1] Using append[] method

This method takes in a single item and adds it to the end of the list. It doesn’t return a new list but just modifies the list in place[thanks to its mutability].

>>>l = list[] # create empty list >>> l [] >>> l.append[4] # add an integer >>> l [4] >>> l.append[[0,1]] # add a list >>> l [4, [0, 1]] >>> l.append[4 < 2] # add the result of an expression >>> l [4, [0, 1], True] >>> l.append[x for x in range[3]] # add result of a tuple comprehension >>> l [4, [0, 1], True, <generator object <genexpr> at 0x7f71fdaa9360>]

Few things to note from the example above:

  • Items here can be expressions, data types, sequences, and many more.
  • The append[] method has a time complexity of [0]1. Meaning it is constant.

#2] Using extend[] method

This method takes in an iterable as its argument and adds all the items from it to the end of the list. This method is mostly used when we want to add individual items of a sequence into a list

Basically, the extend[] method iterates over its argument and appends each item to the list. Just like the append[] method, it doesn’t return a new list but modifies the list in place.

>>> l1 = [3,2,5] # create a list of items >>> l1 [3, 2, 5] >>> l2 = [0,0,-1] # create a second list of items >>> l2 [0, 0, -1] >>> str = "hello" # create a string[iterable] >>> str 'hello' >>> l1.extend[l2] # append all items from l2 to l1 >>> l1 [3, 2, 5, 0, 0, -1] >>> l1.extend[str] # append all items from str to l1 >>> l1 [3, 2, 5, 0, 0, -1, 'h', 'e', 'l', 'l', 'o']

Few things to note from the above example:

  • A string is iterable, so our extend[] method will iterate over its characters.
  • The extend[] method has a time complexity of [0]K where K is the length of its argument.

Accessing Items From A List

Indexing and slicing are the most common means that are used to access lists. We can also access items in a list with loops like the for loop.

#1] Indexing

A Python list uses the zero-based numbering system. Meaning, all its items are uniquely identified by an index number starting from 0 to n-1 where n is the length of the list.

Consider the list below:

>>> colors = ['red','blue','green','yellow','black'] # create list >>> colors ['red','blue','green','yellow','black'] >>> len[colors] # get list length 5

The table below shows their respective indices in the zero-based numbering of a list.

Itemredbluegreenyellowblack

Index01234

From the table above, we see that the first item[‘red’] is at the index position 0 and the last item[‘black’ ] is at index position 4[n-1] where n=5[length of the object colors].

As we saw in the characteristic section above, Python lists are ordered sequences. This allows us to use indexing to access and manipulate its item easily.

Let’s use indexing to access items at particular indices of the colors object created above.

>>> colors # original list ['red','blue','green','yellow','black'] >>> colors[0] # access item at index 0 'red' >>> colors[4] # access item at index 4 'black' >>> colors[9] # access item at index 9 Traceback [most recent call last]: File "<stdin>", line 1, in <module> IndexError: list index out of range

Note: The last statement above is trying to access an item at index position 9 from a list object of length 5. In Python list, accessing an item at an index that doesn’t exist will raise the IndexError exception.

An important concept of indexing is that we can use negative indexing i.e. we can access items of a list in a reversed manner starting at -1 for the last item and ending at -n for the last item where n is the list object’s length.

In the above table, if we use negative indexing, it will look as shown below:

Itemredbluegreenyellowblack

Index-5-4-3-2-1

Let’s use negative indexing to access some items of the color object created above.

>>> colors # original list ['red','blue','green','yellow','black'] >>> colors[-1] # access item and index -1[first item counting backward] 'black' >>> colors[-3] # access item at index -3[third item counting backward] 'green' >>> colors[-5] # access item at index -5 [last item counting backward] 'red'

#2] Slicing

Unlike indexing that only returns one item, slicing on the other hand can return a range of items.

It has the following syntax:

L[n:m]

When n is the index number where the slice starts[defaults to 0], and m is the exclusive index number where the slice ends[defaults to length-1]. They are separated by a colon[:]

Consider the below example that uses slicing to access items at particular indices of the colors object created above.

>>> colors # original list ['red','blue','green','yellow','black'] >>> colors[0:2] # get first two items ['red', 'blue'] >>> colors[1:4] # get items at index 1,2 and 3 ['blue', 'green', 'yellow'] >>> colors[2:len[colors] # get items from index 2 to the last item ['green', 'yellow', 'black'] >>> colors[3:4] # get one item at index 3. Same as colors[3] ['yellow'] >>>

In the syntax L[n:m], n defaults to 0, and m defaults to the length of the list. So, in examples 1 and 3 above, we could omit n and m as colors[:2] and colors[2:] respectively. Or [:] which in this case returns a shallow copy of the entire list object.

We can also use negative index numbers while slicing lists. This is typically used when we want to access the list in a reversed manner.

>>> colors # original list ['red','blue','green','yellow','black'] >>> colors[-3:-2] ['green'] >>> colors[-2:] ['yellow', 'black']

Also, there is a third parameter that slicing supports called step[s]. It defines how many items to move forward after the first item is retrieved from the list. It defaults to 1.

L[n:m:s]

Using our same color list defined above, let’s use the slice’s third parameter to move 2 steps.

>>> colors # original list ['red','blue','green','yellow','black'] >>> colors[0:3:2] ['red', 'green']

#3] Using loops

Loops are mostly used to access items in a list in order to manipulate the items. So, in case we want to operate on the items of a list, we can use the for loop to access the items and pass them over to be operated on.

Say, we want to count the number of letters for each item. We can use the for loop to accomplish that.

Open an editor and paste the code below:

def count_letters[l]: count = {} # define a dict to hold our count for i in l: # loop through the list count[i] = len[i] # for each item, compute its length and store it in the dict return count # return the count if __name__ == '__main__': colors = ['red', 'blue', 'green', 'yellow', 'black'] print[count_letters[colors]]

Output

To end this section, let’s look at two cool stuff that can be done with slicing.

The is the basic way to use the copy[] method of the list object or the built-in function copy.copy. However, this can be achieved by slicing.

>>> colors # original list ['red','blue','green','yellow','black'] >>> colors_copy = colors[:] # make a shallow copy >>> colors_copy ['red', 'blue', 'green', 'yellow', 'black'] >>> colors_copy[0] = 0 # modify item at index 0 by changing its value to 0 >>> colors_copy # the copied version now has 0 at index 0 [0, 'blue', 'green', 'yellow', 'black'] >>> colors # the original version is unchanged ['red', 'blue', 'green', 'yellow', 'black'] >>>

The basic way is to use the reverse method of the list object or the built-in function reversed[]. However, this can be achieved by slicing.

>>> colors # original list object ['red', 'blue', 'green', 'yellow', 'black'] >>> colors[::-1] # returns a reversed shallow copy of the the original list ['black', 'yellow', 'green', 'blue', 'red'] >>>

Removing Items From A List

As we can add as many items to a list, they can also be removed from a list. The three ways by which items can be removed are:

#1] Using the del statement

It has the following syntax:

del target_list

The target list[target_list] can be the entire list[in case you want to delete the list] or an item or items in a list[in this case you use indexing or slicing].

Consider the example below.

Say, we want to delete some items from the colors list created above.

>>> colors # original list ['red', 'blue', 'green', 'yellow', 'black'] >>> c_copy = colors[:] # make a shallow copy to work on >>> del c_copy[0] # delete item at index 0 >>> c_copy ['blue', 'green', 'yellow', 'black'] >>> del c_copy[0:2] # delete items at index 0 and 1[slicing] >>> c_copy ['yellow', 'black'] >>> del c_copy[:] # delete all items in a list. Same as ‘c_copy.clear[]’ [] >>> del c_copy # delete the list object >>> c_copy # access object that doesn't exist Traceback [most recent call last]: File "<stdin>", line 1, in <module> NameError: name 'c_copy' is not defined >>>

Note: The del statement deletes in place i.e., it will modify the original list object rather than returning a new list object.

#2] Using the list.remove[x]

It removes the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.

This method is used mostly to remove items from a list by name, unlike the del statement that uses indexing and slicing.

>>> colors # original list ['red', 'blue', 'green', 'yellow', 'black'] >>> c_copy = colors[:] # create shallow copy to work on >>> c_copy ['red', 'blue', 'green', 'yellow', 'black'] >>> c_copy.remove['blue'] # remove first item with name 'blue' >>> c_copy ['red', 'green', 'yellow', 'black'] >>> c_copy.remove['blue'] # try to remove item that doesn't exist Traceback [most recent call last]: File "<stdin>", line 1, in <module> ValueError: list.remove[x]: x not in list >>>

Note: The list object remove[] method deletes in place i.e., it will modify the original list object rather than returning a new list object.

#3] Using list.pop[[i]]

It removes and returns the item at the given position in a list object. If no i[index] is provided, it removes and returns the last item in the list.

Note: The square bracket around i above doesn’t mean a list of i, rather it means i is optional.

>>> colors # original list ['red', 'blue', 'green', 'yellow', 'black'] >>> c_copy = colors[:] # make a shallow copy to work on >>> c_copy ['red', 'blue', 'green', 'yellow', 'black'] >>> c_copy.pop[3] # pop out the item at index 3 'yellow' >>> c_copy ['red', 'blue', 'green', 'black'] >>> c_copy.pop[] # pop out the last item in the list 'black' >>> c_copy ['red', 'blue', 'green'] >>>

Note:The list.pop[[i]] method deletes in place i.e., it will modify the original list object rather than returning a new list object. Also, it returns the item removed from the list

Replacing Items From A List

Replacing items is pretty simple. In one of the above sections, we saw indexing and slicing. These can be used to access and remove items from a list.

#1] Replace using indexing

L[index] = value>>> colors # original list ['red', 'blue', 'green', 'yellow', 'black'] >>> c_copy = colors[:] # make a shallow copy to work on >>> c_copy ['red', 'blue', 'green', 'yellow', 'black'] >>> c_copy[0] = 'brown' # replace item at index 0 with 'brown' >>> c_copy ['brown', 'blue', 'green', 'yellow', 'black'] >>>

#2] Replacing using slicing

L[n:m] = value

Note: Value should be an iterable, or else the TypeError exception will be raised.

>>> colors # original list ['red', 'blue', 'green', 'yellow', 'black'] >>> c_copy = colors[:] # make a shallow copy to work on >>> c_copy[0:2] = ['brown'] # replace items at index 0 and 1 with 'brown' >>> c_copy ['brown', 'green', 'yellow', 'black'] >>> c_copy[1:3] = ['white','purple'] # replace items at index 1 and 2 with 'white' and 'purple' >>> c_copy ['brown', 'white', 'purple', 'black'] >>> c_copy[1:4] = ['white','purple'] # replace items at index 1,2 and 3 with 'white' and 'purple'. Here we replace 3 items with 2 items >>> c_copy ['brown', 'white', 'purple'] >>>

Frequently Asked Questions

Q #1] What is a list of lists in Python?

Answer: A list of lists in Python is a list that contains lists as its item.

For example

[['a','b'],['c','d']]

It can also be referred to as a nested list.

Q #2] How do you declare a list in Python?

Answer: In Python, a list can be declared in two ways. Either by using the built-in function list[] or by using the bracket notation []. list[] takes in an iterable and [] takes in items of any type separated by a comma.

[pytyon]>>> list['hello'] # a string is iterable ['h', 'e', 'l', 'l', 'o'] >>> [3,4,5,23] # numbers are separated by comma [3, 4, 5, 23] >>> [/python]

Q #3] Can you put a list in a list Python?

Answer: Yes, we can put a list inside a list. As a matter of fact, a list is a container sequence that takes in items of any data type.

Q #4] What does list[] do in Python?

Answer: list[] is a built-in function in Python that creates a list object. It takes in an iterable as its argument.

>>> list[[3,2,4]] # The iterable object here is a tuple. [3, 2, 4] >>>

Q #5] Can a Python list contain different types?

Answer: A list is a container sequence that takes in items of any data types[list, tuple, integer, float, strings, etc]

Lists are just like dynamically sized arrays, declared in other languages [vector in C++ and ArrayList in Java]. Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation.

List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. Each element in the list has its definite place in the list, which allows duplicating of elements in the list, with each element having its own distinct place and credibility.

Note- Lists are a useful tool for preserving a sequence of data and further iterating over it.

Table of content:

  • Creating a List
  • Knowing the size of List
  • Adding Elements to a List:
    • Using append[] method
    • Using insert[] method
    • Using extend[] method
  • Accessing elements from the List
  • Removing Elements from the List:
    • Using remove[] method
    • Using pop[] method
  • Slicing of a List
  • List Comprehension
  • Operations on List
  • List Methods

by · July 10, 2019