Python List Examples – Insert, Append, Length, Index, Remove, Pop

by Himanshu Arora on June 21, 2013

Lists in Python language can be compared to arrays in Java but they are different in many other aspects. Lists are used in almost every program written in Python. In this tutorial we will understand Python lists through practical examples.

We will cover the following in this article :

  • How to define a list
  • How to add elements to a list
  • How access sub lists
  • How to search within lists
  • How to delete elements from a list
  • Operators and lists

1. Create a Python List

Defining a List in Python is easy. You just need to provide name of the list and initialize it with values. Following is an example of a List in Python :

>>> myList = ["The", "earth", "revolves", "around", "sun"]
>>> myList
['The', 'earth', 'revolves', 'around', 'sun']

So you can see that a list named ‘myList’ was created with some elements.

Lists in python are zero indexed. This means, you can access individual elements in a list just as you would do in an array. Here is an example :

>>> myList[0]
>>> myList[4]

Lists cannot be accessed beyond the rightmost index boundary. Here is an example :

>>> myList[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

So we see that when we tried to access myList index 5, an error was thrown saying that this index is out of range.

But, on the other hand, if you try to access value at a negative index then values from the rightmost index can be accessed backwards. Here is an example:

>>> myList[-1]

So we see that index -1 was translated into index ’4′ and corresponding value was produced in output.

If you are new to Python, you should start by writing a Python hello world program, and understanding Python variables and strings.

2. Add Elements to a List

One can use the method insert, append and extend to add elements to a List.

The insert method expects an index and the value to be inserted. Here is an example of insert :

>>> myList.insert(0,"Yes")
>>> myList
['Yes', 'The', 'earth', 'revolves', 'around', 'sun']

So we see the value ‘yes’ was inserted at the index 0 in the list and all the other elements were shifted accordingly.

The append method can take one or more elements as input and appends them into the list. Here is an example :

>>> myList.append(["a", "true"])
>>> myList
['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true']]

So, the two values were appended towards the end of the list. Note that whether we add one element or multiple elements to the list, if we have used append then they will be added as a single element only. This can be proven if we try to check the length of myList now :

>>> len(myList)

So we see that though we added two elements but they are counted as a single element (or a sub-list) in myList.

The other method that can be used to add elements to list is extend. Like append, it also expects one or more values as input. But, unlike append, all the elements are added as individual elements. Here is an example :

>>> myList.extend(["statement", "for", "sure"])
>>> myList
['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']
>>> len(myList)

So we see that each element got added as a separate element towards the end of the list.

3. Slice Elements from a List

Python also allows slicing of the lists. You can access a part of complete list by using index range. There are various ways through which this can be done. Here are some examples :

If it is required to access a sub-list from index 1 to index 3 then it can be done in following way:

>>> myList[1:4]
['The', 'earth', 'revolves']

Note that the index 4 was passed instead of 3 because if we pass index range x:y then values up to index y-1 are printed.

Now, if it is required to access first ‘n’ elements of the list, then there is no need to provide index ’0′, only the value of ‘n’ is required. Here is an example :

>>> myList[:4]
['Yes', 'The', 'earth', 'revolves']

So we see that first three elements were accessed.

Similarly, if last ‘n’ elements are required to be accessed then only starting index is required. Here is an example :

>>> myList[4:]
['around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']

So we see that all the elements beginning from index 4 till end of the list were displayed.

If neither starting index, nor the ending index is provided then complete list is displayed. Here is an example :

>>> myList[:]
['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']

4. Search the Lists and find Elements

Lists can easily be searched for values using the index method that expects a value that is to be searched. The output is the index at which the value is kept.

Here is an example :

Here we try to search the list for value ‘revolves’.

>>> myList.index("revolves")

So we see that the corresponding index was displayed in the output.

If some value is not found then an error is displayed. Here is an example :

>>> myList.index("a")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'a' is not in list

Here is how you can search a sub list :

>>> myList.index(["a", "true"])

If it is desired to just whether an element is present in a list, it can be done in following way :

>>> "sun" in myList

So we see that ‘True’ was returned as ‘sun’ was present in the list.

5. Delete Elements from the List

Python provides the remove method through which we can delete elements from a list. It expects the value which is required to be deleted.

Here are some examples :

>>> myList
['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']
>>> myList.remove("Yes")
>>> myList
['The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']
>>> myList.remove("statement")
>>> myList
['The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'for', 'sure']

Here we see that remove can be used to easily delete elements in list.

Here is how a sub list can be deleted :

>>> myList.remove(["a", "true"])
>>> myList
['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure']

So we see that the sub list was deleted from the original list.

If it is required to access the last element and then to delete it, this can be done through pop method.

>>> myList.pop()
>>> myList
['The', 'earth', 'revolves', 'around', 'sun', 'for']

So we see that the value was displayed and  deleted simultaneously.

6. Python List Operators

Python allows to use mathematical operators like +, * etc to be used with lists.

Here are some examples :

>>> myList
['The', 'earth', 'revolves', 'around', 'sun', 'for']
>>> myList = myList + ["sure"]
>>> myList
['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure']
>>> myList += ["."]
>>> myList
['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure', '.']
>>> myList *= 2
>>> myList
['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure', '.', 'The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure', '.']

So we see that through + operator elements could be added to the list and through * operator we can add the complete list repeatedly towards the end.

Linux Sysadmin Course Linux provides several powerful administrative tools and utilities which will help you to manage your systems effectively. If you don’t know what these tools are and how to use them, you could be spending lot of time trying to perform even the basic administrative tasks. The focus of this course is to help you understand system administration tools, which will help you to become an effective Linux system administrator.
Get the Linux Sysadmin Course Now!

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 5 comments… read them below or add one }

1 A. D. Baines June 22, 2013 at 12:29 am

This is great for all the programming I am trying to learn. Thanks a lot.

2 P June 22, 2013 at 1:39 am


3 Ethan June 24, 2013 at 6:07 am

Clear and helpfull. It is also advised the idea in R, in which I use S4 for project. Thank you Himanshu

4 J February 1, 2014 at 6:15 am

When you describe removing a sublist, I almost thought I had found the answer I was googling for. But alas I need to remove an item from a sublist.

How might I remove all ‘b’s from

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

to get:

[['a', 'c'], ['d'], ['a', 'e']]



5 crystal November 20, 2014 at 6:06 pm

Great help. One thing, though. Is there a function that would allow me to append to one list, but also add that new item to another list? I am trying to write a program that serves as a bilingual dictionary for my students, so if they add the Spanish definition for dog it will append to the English to Spanish list, but I also want it to be added to the Spanish to English list. Can we do that in python?

Leave a Comment

Previous post:

Next post: