≡ Menu

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

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]
'The'
>>> myList[4]
'sun'

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]
'sun'

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)
7

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)
10

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")
3

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"])
6

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

>>> "sun" in myList
True

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()
'sure'
>>> 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.

Add your comment

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

Comments on this entry are closed.

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

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

  • P June 22, 2013, 1:39 am

    Nice!

  • Ethan June 24, 2013, 6:07 am

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

  • J February 1, 2014, 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’]]

    ?

    Thanks

  • crystal November 20, 2014, 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?

  • Vijay July 21, 2015, 11:28 pm

    was very useful

  • Ahmed Zaki November 30, 2015, 2:43 am

    Thank You very much! it very nice of You to share knowledge as You helped me a lot, wish You all the best Sir, Greetings from Egypt.

  • T February 3, 2016, 12:57 pm

    You’re very good at explaining this. Thank you

  • B March 23, 2016, 11:54 am

    To answer J’s question (even if two years old!):

    A = [[‘a’,’b’,’c’],[‘b’,’d’],[‘a’,’e’]]
    B = [A[i].remove(‘b’) if ‘b’ in A[i] else A[i] for i in range(len(A))]

  • Anonymous April 16, 2016, 10:45 pm

    Sir can you tell how to declare empty list?

  • Diego Nassisi May 16, 2016, 11:48 pm

    Neat-o!!!!

  • mukil December 9, 2016, 4:53 am

    Thank u so much , it was very useful

  • nick January 15, 2017, 4:26 pm

    thanks for the help 🙂

  • Victor February 9, 2017, 6:57 pm

    Good tutorial! This is helping me a lot.

    However, “len(myList)” does not print anything for me in 3.6.0, I need to use

    “print(len(myList))”

  • Jasper April 12, 2017, 4:35 pm

    Beautiful examples cleared all my doubts

  • TREVOR May 1, 2017, 11:59 am

    Sir can you tell how to declare empty list?

  • Anonymous May 7, 2017, 6:11 am

    how do you add a new list

  • tobiloba June 27, 2017, 12:46 pm

    U can add a new list with either of these append, insert and extend just declare ur newlist = []
    Newlist.append (‘b’)
    Print (Newlist)
    U shud av sumtin like dis:
    b