Python Lists

List in Python is a built-in data type, used to store multiple items in a single variable. That is, when we need to store collection of data in a single variable, then we use list.

Note - List items are ordered, changeable, and allows duplicates.

List items are ordered, means that all the items (elements or values) of the list are numbered. For example, if there is a list named mylist, then mylist[0] refers to the first element, whereas the mylist[1] refers to the second element, and so on.

List items are changeable, means that we can change the items of the list further, after initialization.

List items allows duplicate values, means that in a particular list, there may be two or more items with same values.

Create an Empty List in Python - Syntax

An empty list can be created in following two ways:

  1. Using square brackets. That is, [ ]
  2. Using list() constructor

Create an Empty List using Square Bracket

Here is the syntax to create an empty list in Python, using the square bracket:

listName = []

Create an Empty List using list() Constructor

To create an empty list using list() constructor, then use following syntax:

listName = list()

Create a List in Python - Syntax

Here is the syntax to create a list with values in Python:

listName = [value1, value2, value3, ..., valueN]

where value1, value2, value3 etc. can be of any data type such as integer, floating-point, boolean, string, character etc. Also, can be a list too.

Another way that we can create a list, is by using the list() constructor. Here is the syntax:

listName = list((value1, value2, value3, ..., valueN))

Note - Keep the double bracket in mind.

Create and Print a List in Python - Example

This is the first example of this article on list. This example program creates a list and then prints the list as it is, on the output screen.

mylist = [1, 2, 3, 4, 5]
print(mylist)

mylist = [1, 'c', True, "codescracker", 12.4, 43]
print(mylist)

The same program can also be created in this way:

mylist = list((1, 2, 3, 4, 5))
print(mylist)

mylist = list((1, 'c', True, "codescracker", 12.4, 43))
print(mylist)

The snapshot given below shows the output produced by above Python code on list:

python list create and print

As already told, that the list is a kind of built-in data types in Python. The list can be used to store multiple values in a single variable, as shown in the program given above. That is, the values 1, 2, 3, 4, 5 is initialized to a single variable say mylist using the first statement. Similar things done to define a list using third statement.

Note - List items are indexed in a way that the first item stored at 0th index, whereas the second item stored at 1st index, and so on.

Can List Contain Elements of Different Types ?

Yes, of course. The list elements can be of same or of different types. Here is an example:

x = [12, 'c', 32.54, "codes", True]
print(x)

The output would be:

[12, 'c', 32.54, 'codes', True]

Python Access and Print List Element using Index

The element of a list can be accessed using its index in either from forward indexing or through backward (negative) indexing. The snapshot given below shows both forward and backward indexing:

python list slicing indexing

That is, to access the very first element of a list named mylist, we need to use mylist[0], whereas to access the last element of a list, we need to use mylist[-1]. Here is an example showing how to access and print the list elements using forward indexing.

mylist = [1, 2, 3, 4, 5]
print(mylist[0])
print(mylist[1])
print(mylist[2])
print(mylist[3])
print(mylist[4])

The output produced by this Python program is:

1
2
3
4
5

Here is another program shows how we can access elements of a list, using backward indexing:

mylist = [1, 2, 3, 4, 5]
print(mylist[-1])
print(mylist[-2])
print(mylist[-3])
print(mylist[-4])
print(mylist[-5])

Here is the output produced by this program:

5
4
3
2
1

I know the above program looks weird, because what if there are more elements in the list, then writing the print() statement along with index number, for all the elements, is not possible, and also takes too much time. Therefore, we need to use loop to print list elements. The example program based on it is given below.

Python Print List Elements using Loop

This program does the same job as of previous program. The only difference is its approach. That is, this program uses for loop to do the job:

mylist = [1, 2, 3, 4, 5]
for element in mylist:
    print(element)

You'll get the same output as of previous program's output.

Print all Elements of List using Loop, in Single Line

Most of the time, we need to print all list elements in a single line. Therefore this program shows how to code in Python, so that the list elements gets printed in single line, instead of multiple:

mylist = [1, 2, 3, 4, 5]
for element in mylist:
    print(element, end=" ")

Here is its output:

1 2 3 4 5

Note - The end parameter is used to skip insertion of an automatic newline, using print().

Python Create and Print a List with User Input

Now let's create another example program on list, that allows user to define the size and elements of a list. The defined list elements will get printed back on the output screen:

print("How many element to store in the list: ", end="")
n = int(input())
print("Enter", n, "elements for the list: ", end="")
mylist = []
for i in range(n):
    val = input()
    mylist.append(val)

print("\nThe list is:")
for i in range(n):
    print(mylist[i], end=" ")

Sample run with user input 5 as size of list, and 10, 20, 30, 40, 50 as its five elements, is shown in the snapshot given below:

python list create list with user input

Python List Length - Find Length of a List

The len() function plays an important role in most of the program in Python when working with list, specially when working with a list whose elements are defined by user at run-time of the program. Because in that case, the function len() finds the length of the list, and that length plays of course a crucial role most of the time. Let's take a look at one of the simplest example, uses len() function:

mylist = [1, 2, 3, 4, 5]
print("\nLength of List =", len(mylist))

Following is its sample output:

Length of List = 5

Another way to find and print the length of a list, without using len() method, is:

mylist = [1, 2, 3, 4, 5]
count = 0
for element in mylist:
    count = count+1
print("\nList contains", count, "items.")

The output produced by above program is:

List contains 5 items.

Python List Slicing - Forward

Here is the syntax to slice a list in Python:

listVariable[startIndex, endIndex, step]

where startIndex is the starting index number from where the slice to start. The element at this index is included. The endIndex is the last index number at which the slice to stop. The element at this index is excluded. And the step is used when we need to slice items of a list, along with skipping every nth element in between, while slicing.

Note - By default, the startIndex value is 0, the endIndex value is equal to the length of the list, and step value is equal to 1.

Before consider an example of list slicing in Python. Let's have a look at the following list:

mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Now:

  • mylist[0:] gives or returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • mylist[:] gives [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • mylist[:10] gives [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • mylist[2:4] gives [3, 4]
  • mylist[2:8:3] gives [3, 6]
  • mylist[2:9:3] gives [3, 6, 9]
  • mylist[::3] gives [1, 4, 7, 10]

Now here is an example of list slicing in Python. This program sliced a list named mylist in multiple ways, so that all the concept of list slicing (forward) will easily get cleared using a single program:

mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print("The original list is:")
print("mylist =", mylist)

print("\nList slicing example:")
print("mylist[0:] =", mylist[0:])
print("mylist[:] =", mylist[:])
print("mylist[:10] =", mylist[:10])
print("mylist[2:4] =", mylist[2:4])
print("mylist[2:8:3] =", mylist[2:8:3])
print("mylist[2:9:3] =", mylist[2:9:3])
print("mylist[::3] =", mylist[::3])

The snapshot given below shows the sample output produced by above Python code, on list slicing:

python list slicing example code

Python List Slicing - Backward

The element at index -1 will get considered as the last element of the list, whereas the element at index -lengthOfList will get considered as the first element of the list. Here is an example of list slicing using negative indexing:

mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print("The original list is:")
print("mylist =", mylist)

print("\nList slicing example (using backward indexing):")
print("mylist[-10:] =", mylist[-10:])
print("mylist[-8:] =", mylist[-8:])
print("mylist[:] =", mylist[:])
print("mylist[:-1] =", mylist[:-1])          # second index's value is excluded
print("mylist[:-4] =", mylist[:-4])
print("mylist[-4:-2] =", mylist[-4:-2])
print("mylist[-8:-2:3] =", mylist[-8:-2:3])
print("mylist[-9:-2:3] =", mylist[-9:-2:3])
print("mylist[-10:-1:3] =", mylist[-10:-1:3])
print("mylist[::3] =", mylist[::3])

Sample run of above Python code is shown in the snapshot given below:

python list slicing backward indexing

Python List Append - Add New Element to a List

Because list items are changeable, therefore we can add required elements to a list anytime. Elements can be added either at the end of a list or at a given index. Let's start with adding an element of a list at the end of a list in Python.

Add New Element at the End of a List

The append() method is used when we need to add an element at the end of a list. Here is an example:

mylist = [1, 2, 3, 4, 5]

print("The original list is:")
print("mylist =", mylist)

print("\nEnter an Element to add: ", end="")
element = int(input())
mylist.append(element)

print("\nNow the list is:")
print("mylist =", mylist)

The snapshot given below shows the sample run of above Python program, with user input 10 as element to add:

python list add element to list

Add New Element in a List at Given Index

The insert() method is used when we need to insert an element at specified index in a list. Here is an example:

mylist = [1, 2, 3, 4, 5]

print("The original list is:")
print("mylist =", mylist)

print("\nEnter an Element to add: ", end="")
element = int(input())
print("At what index ? ", end="")
index = int(input())

if index <= len(mylist):
    mylist.insert(index, element)
    print("\nNow the list is:")
    print("mylist =", mylist)
else:
    print("\nInvalid Index Number!")

Sample run with user input 500 as element and 3 as index number to add a new element to the list, is shown in the snapshot given below:

python list add new element to specified position

Here is another example demonstrating how an element can be inserted at a specified index in a list.

mylist = ['c', 'o', 'd', 's', 'c']

print("The original list is:")
print("mylist =", mylist)

mylist.insert(3, 'e')
print("\n1. Now the list is:")
print("mylist =", mylist)

mylist.insert(6, 'r')
print("\n2. Now the list is:")
print("mylist =", mylist)

mylist[7:10] = ['a', 'c', 'k', 'e']
print("\n3. Now the list is:")
print("mylist =", mylist)

mylist.insert(11, 'r')
print("\n4. Now the list is:")
print("mylist =", mylist)

To add element at particular index, without removing the previous value available at that index, use insert(). While using insert() to insert an element at specified index, all the elements after that index moved to one index forward.

Python Replace Single or Multiple Elements in a List

Use direct initialization of single or multiple values to a single or multiple indexes to add new element(s) to a list. But the element(s) get replaced available at index(es) that was used for the initialization. Here is its sample program, demonstrating the concept:

mylist = ['c', 'o', 'd', 's', 'c']

print("The original list is:")
print("mylist =", mylist)

mylist[3] = 'x'
print("\n1. Now the list is:")
print("mylist =", mylist)

mylist[3:5] = ['e', 's']
print("\n2. Now the list is:")
print("mylist =", mylist)

mylist[6:12] = ['c', 'r', 'a', 'c', 'k', 'e', 'r']
print("\n3. Now the list is:")
print("mylist =", mylist)

mylist[3] = 'x'
print("\n4. Now the list is:")
print("mylist =", mylist)

mylist[2:8] = 'z'
print("\n5. Now the list is:")
print("mylist =", mylist)

mylist[1:6] = ['a', 'b']
print("\n6. Now the list is:")
print("mylist =", mylist)

mylist[:] = 'x'
print("\n7. Now the list is:")
print("mylist =", mylist)

Let's concentrate on the output of above program, to get the concept.

The original list is:
mylist = ['c', 'o', 'd', 's', 'c']

1. Now the list is:
mylist = ['c', 'o', 'd', 'x', 'c']

2. Now the list is:
mylist = ['c', 'o', 'd', 'e', 's']

3. Now the list is:
mylist = ['c', 'o', 'd', 'e', 's', 'c', 'r', 'a', 'c', 'k', 'e', 'r']

4. Now the list is:
mylist = ['c', 'o', 'd', 'x', 's', 'c', 'r', 'a', 'c', 'k', 'e', 'r']

5. Now the list is:
mylist = ['c', 'o', 'z', 'c', 'k', 'e', 'r']

6. Now the list is:
mylist = ['c', 'a', 'b', 'r']

7. Now the list is:
mylist = ['x']

Add Multiple Elements at the End of a List at Once

The extend() function is used when we need to add multiple elements at the end of a list, without converting the list into a nested list. Here is an example:

mylist = [1, 2, 3]
mylist.extend([4, 5])
print(mylist)
[1, 2, 3, 4, 5]

Add Two List

The + operator helps in addition of the two lists. Below is an example of list addition in Python:

listOne = ['p', 'y', 't']
listTwo = ['h', 'o', 'n']

listThree = listOne + listTwo
print(listThree)

listOne = listOne + listTwo
print(listOne)

Here is its sample output:

['p', 'y', 't', 'h', 'o', 'n']
['p', 'y', 't', 'h', 'o', 'n']

Python List Remove

Like adding an element in a list, sometime we also need to remove an element from a list. The list element can be removed in either of the two ways:

  1. using the remove() method
  2. using the pop() method

Remove Element from a List using remove()

The remove() method is used when we need to remove an element from a list, using element by value.

mylist = [11, 22, 33, 44, 55]
print("The list is:")
print(mylist)

mylist.remove(44)
print("\nNow the list is:")
print(mylist)

The output is:

The list is:
[11, 22, 33, 44, 55]

Now the list is:
[11, 22, 33, 55]

Remove Element from List using pop()

The pop() method is used when we need to pop an element from a list, using element by index.

mylist = [11, 22, 33, 44, 55]
print("The list is:")
print(mylist)

mylist.pop(3)
print("\nNow the list is:")
print(mylist)

You'll get the same output as of previous program's output.

Delete Multiple Items from a List at Once using del Keyword

The del keyword is used when we need to delete multiple elements from a list. The keyword del can also be used to delete the whole list. Here is an example:

x = ['p', 'y', 't', 'h', 'o', 'n']
print(x)
del x[1]
print(x)
del x[1:4]
print(x)
del x

The output produced by this program is given below:

['p', 'y', 't', 'h', 'o', 'n']
['p', 't', 'h', 'o', 'n']
['p', 'n']

After using the del x statement, the whole list x gets deleted. And if you try to print x, then the program produces an error like this:

python list example code program

This output produced, after adding print(x) as the last statement of the above program.

Python List Functions

These are the functions that can be used while working with list in Python. All these functions are important in list point of view. I've described about all these functions, in very brief. To learn in detail, you can refer to its separate tutorial.

  • list() - Converts a sequence to a list
  • len() - Returns the length of a list
  • append() - Used to add new element at the end of a list.
  • extend() - Used to add multiple elements or an iterable at the end of a list
  • insert() - Inserts an element at specified index
  • remove() - Removes the first occurrence of an element with specified value, from a list
  • pop() - Used to remove an item from the list
  • max() - Returns the maximum item in an iterable, or the maximum between/among two/multiple arguments
  • min() - Returns the minimum item in an iterable, or the minimum between/among two/multiple arguments
  • clear() - Used to empty the list
  • index() - Returns the index number of the first occurrence of a specified value in a list
  • count() - Returns the number of occurrence of a particular element in a list
  • sort() - Used to sort a list
  • sorted() - Returns the sorted list
  • reverse() - Used to reverse the elements of a list
  • reversed() - Returns the reversed list
  • copy() - Used to copy a list

Python Nested List - List of Lists

A list can be nested inside another list. That is, when we add a list itself instead of an element, when initializing the elements to a list, then the list becomes a nested list. Here is an example:

mylist = [1, [2, 3, 4], 5, 6, [7, 8, 9, 10]]
print("Direct:")
print(mylist)

print("\nUsing loop:")
for x in mylist:
    print(x)

Here is its sample output:

Direct:
[1, [2, 3, 4], 5, 6, [7, 8, 9, 10]]

Using loop:
1
[2, 3, 4]
5
6
[7, 8, 9, 10]

Here is another example of nested list (list of list(s)):

mylist = [1, [2, 3, 4], 5, 6, [7, 8, 9, 10]]
print(mylist[0])
print(mylist[1][0])
print(mylist[1][1])
print(mylist[1][2])
print(mylist[2])
print(mylist[3])
print(mylist[4][0])
print(mylist[4][1])
print(mylist[4][2])
print(mylist[4][3])
1
2
3
4
5
6
7
8
9
10

This is the last example of nested list or list of lists in Python. This program uses a list named books_list in which all the elements are itself a list of 2 elements each.

books_list = [["Java", "$128"], ["C++", "$99"], ["Python", "$169"]]
ch = None
while ch != "3":
    print("\n1. Show Books List")
    print("2. Add a Book")
    print("3. Exit")
    print("Enter Your Choice (1-3): ", end="")
    ch = input()
    if ch == "1":
        print("\nBook\t\t Price")
        for book in books_list:
            book_name, book_price = book
            print(book_name, "\t\t", book_price)
    elif ch == "2":
        print("\nEnter the Name of Book: ", end="")
        book_name = input()
        print("Enter the Price: ", end="")
        book_price = input()
        book_price = "$" + book_price
        add_book = book_name, book_price
        books_list.append(add_book)
    elif ch == "3":
        print("\nOk!")
        break
    else:
        print("\nInvalid Choice!")

The sample run is shown in the snapshot given below:

python nested list example program code user

Python List Comprehension

The word comprehension means the ability to understand something. After understanding the list, it becomes easy to understand the list comprehension topic.

Basically the list comprehension is used, most of the times by professional Python programmer, as it allows to create a list with multiple elements in a single statement or few statements. In short, list comprehension is a concise way to create a list.

Definition - A list comprehension is an expression available inside a square bracket. The expression uses a for loop to create a list using list comprehension.

Python List Comprehension Syntax

Here is the syntax to create a list using list comprehension:

mylist = [expression for item in iterable if condition == True]

The if condition == True is optional.

Python List Comprehension Example

Here is an example of a list comprehension. This program creates a list named tableOf2 with 10 elements:

tableOf2 = [2 * i for i in range(1, 11)]
print(tableOf2)

If this program will get executed, then the output would be:

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Note - The range() method returns a sequence of numbers. Refer to its separate tutorial, for detail.

Here is another example of list comprehension. This program uses list comprehension to print the table of 1, 2, 3, ..., 10:

for num in range(1, 11):
    table = [num * i for i in range(1, 11)]
    print(table)

The output would be:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
[4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
[6, 12, 18, 24, 30, 36, 42, 48, 54, 60]
[7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
[8, 16, 24, 32, 40, 48, 56, 64, 72, 80]
[9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Here is the last example program of list comprehension. This program uses condition in the expression of list comprehension:

mylist = [x for x in range(100) if x<10]
print(mylist)

Here is its output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The method range() returns a sequence of numbers from 0 to 99. But from all 0, 1, 2, 3, ..., 99, numbers that are less than 10, is initialized as elements of list named mylist.

Python Online Test


« Previous Tutorial Next Tutorial »