A list in Python represents a collection of ordered items. The items can be of varying types such as numbers, strings and even other lists, literally anything that has value can be stored in a list.

Lists are mutable, which means that we can modify them in-place after they are created. In contrast, immutable types like strings and tuples require the creation of a new object in memory each time they are modified. This makes mutable objects more flexible and memory efficient, allowing for faster and more complex data manipulation.

Lists objects are created by enclosing comma separated  items in square brackets []. The following examples demonstrates this.

An empty list:

[]
copy

A list of integers:

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

A list of strings:

["America", "China", "Australia", "Brazil", "South Africa"]
copy

A list of lists:

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

A list of mixed types:

[ 1, "Python", [1, 2, 3], ('Python', 'Javascript', 'Html', 'CSS') ]
copy

As shown  above, one way to create an empty list is to simply use empty square brackets, another way to achieve this is by using the builtin list() function. 

ExampleEdit & Run
L = list()

print( L )
copy
Output:
[] [Finished in 0.010615570936352015s]

This function can also be used to cast other relevant types into lists.

ExampleEdit & Run
L = list('Hello, World!')#string to list
print( L )

L = list((1, 2, 3, 4, 5, 6 ))#tuple to list
print( L )

L = list({1, 2, 3, 4, 5, 6})#set to list
print( L )
copy
Output:
['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!'] [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] [Finished in 0.010139021091163158s]

Operations on Lists.

A wide variety of operations can be performed on lists, thanks to their mutable nature, which allows for efficient in-place modifications. This means that the majority of these operations directly modify the original list rather than creating a new one. We will explore some of the most common list operations.

Concatenation and Repetition

The " + " operator is used in list concatenation.  In this operation, all the elements of the second list operand are appended to the end of the first list.

ExampleEdit & Run
print( [1, 2, 3] + [4, 5, 6] )

print( ['Python', 'Ruby', 'Javascript', 'Swift'] + ['C', 'C++', 'Java', 'Perl']  )

print(  [ (1, 2), (3, 4) ] + [ (5, 6), (7, 8) ] + [ (9, 10), (11, 12) ]  )
copy
Output:
[1, 2, 3, 4, 5, 6] ['Python', 'Ruby', 'Javascript', 'Swift', 'C', 'C++', 'Java', 'Perl'] [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)] [Finished in 0.010316297877579927s]

In list repetition, the " * " operator is used with a list operand and an integer operand. The resulting list contains  elements which are  the original list's elements repeated the number of times specified by the integer operand. 

ExampleEdit & Run
L = [0]
print( L * 3 )

L = [1, 2]
print( L * 5 )

L = ['Javascript', 'CSS', 'Html']
print( L * 2 )
copy
Output:
[0, 0, 0] [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] ['Javascript', 'CSS', 'Html', 'Javascript', 'CSS', 'Html'] [Finished in 0.009802097920328379s]

If 0 is used as the integer operand,  the repetition will result in an empty list.

ExampleEdit & Run
L = [1, 2, 3]

print( L * 0 )
copy
Output:
[] [Finished in 0.009984481148421764s]

 List repetition is especially used to initialize lists with default values.

ExampleEdit & Run
L = [0]
print( L *10 )

L = [False]
print( L * 10 )
copy
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [False, False, False, False, False, False, False, False, False, False] [Finished in 0.010163099970668554s]

Indexing, Slicing and Assignment

Each Element in a list has an index through  which it can be accessed. The first element in the list has an index 0 , the second has an index , and so forth. Lists like other sequences  also support negative indexing, in this case, the last element in the list  has an index -1 , the second last has -2, the third from last has -3 and so forth. 

The length of a list is equal to number of items that it contains. We can use the builtin len() function to get the  list's length, as shown below:

ExampleEdit & Run
L = []
print( len(L) )

L = ["Python"]
print( len(L) )

L = [0, 2, 3, 4] 
print( len(L) )

L = [(0,1), (2, 3), (4, 5), (6, 7), (8, 9)]
print( len(L) )
copy
Output:
0 1 4 5 [Finished in 0.009804623201489449s]

If a list has a length L, the valid indices including negative and positive indices  starts from  -L and ends at L - 1 . Using an index out of this range will result in an IndexError.

Square braces [] are used to access the element at a given index. For example if we have a list L , the syntax is as follows:

L[index]
copy

Accessing the first element.

ExampleEdit & Run
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90]

print( my_list[0] ) # using positive indexing
print( my_list[-len(my_list)] ) #Using negative indexing
copy
Output:
10 10 [Finished in 0.009950153063982725s]

Accessing the last Element.

ExampleEdit & Run
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print( my_list[-1] ) #Using negative indexing
print( my_list[len(my_list) - 1 ] ) #Using positive indexing
copy
Output:
9 9 [Finished in 0.009342323988676071s]

accessing  elements using positive indexing:

ExampleEdit & Run
my_list = ['Python', 'Ruby', 'Javascript', 'Swift', 'C', 'C++', 'Java', 'Perl']

print( my_list[0] )
print( my_list[1] )
print( my_list[2] )
print( my_list[3] )
print( my_list[6] )
copy
Output:
Python Ruby Javascript Swift Java [Finished in 0.01004887418821454s]

Accessing elements using negative indexing: 

ExampleEdit & Run
my_list = ['Python', 'Ruby', 'Javascript', 'Swift', 'C', 'C++', 'Java', 'Perl']\

print( my_list[-1] )
print( my_list[-2] )
print( my_list[-3] )
print( my_list[-6] )
print( my_list[-8] )
copy
Output:
Perl Java C++ Javascript Python [Finished in 0.009480844717472792s]

As we said earlier, using an index outside the valid indices ( -L to L-1 ) will raise an  IndexError:

ExampleEdit & Run
my_list = ['Python', 'Ruby', 'Javascript', 'Swift', 'C', 'C++', 'Java', 'Perl']

my_list[10] #IndexError
my_list[-10] #IndexError
copy
Output:
Traceback (most recent call last):   File "<string>", line 3, in <module> IndexError: list index out of range [Finished in 0.009784841910004616s]

Slicing

While indexing is used to access the element  at a specific index, slicing is used to access all the elements in a given range of indices, a list containing these elements is returned.

The square brackets are still used in slicing, but with a slightly different syntax in order to capture a range. The syntax is as follows;

L[start : stop : step]
copy

All the three arguments, start, stop, and step are integers. The start indicates the index where the slicing will begin, the stop indicates the index where the slicing will end without itself included, and the step indicates the jump value. If any of the arguments are omitted, they take on default values: start defaults to 0, stop defaults to the length of the list , and step defaults to 1.

ExampleEdit & Run
L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print( L[0 : 5 : 1] )
print( L[0 : 5 ] )#step defaults to 1
print( L[3 : 8] )
print( L[0 : 10 : 2] )
print( L[ : 7] ) #start defaults to 0
print( L[5 : ] ) #stop defaults to the list's length
print( L[ : ]  ) #returns the original list
copy
Output:
[0, 1, 2, 3, 4] [0, 1, 2, 3, 4] [3, 4, 5, 6, 7] [0, 2, 4, 6, 8] [0, 1, 2, 3, 4, 5, 6] [5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [Finished in 0.01021629199385643s]

Assignment

Since lists are mutable we can change the value at a given index or slice using assignment. The syntax is as follows:

L[index] = <new value>
L[slice] = <new value>
copy

Doing this overwrites the value at the given index or slice with the new value. If we use slice for assignment, the new value needs to be an iterable such as another list, tuple, set e.t.c.

Index assignment Examples:

ExampleEdit & Run
L =['C', 'C++', 'Java', 'Perl', 'Kotlin', 'Javascript']
L[0] = 'Python'
print(L)

L[-1] = 'C#'
print(L)

L[2] = 'Html'
print(L)
copy
Output:
['Python', 'C++', 'Java', 'Perl', 'Kotlin', 'Javascript'] ['Python', 'C++', 'Java', 'Perl', 'Kotlin', 'C#'] ['Python', 'C++', 'Html', 'Perl', 'Kotlin', 'C#'] [Finished in 0.009666466154158115s]

Slice assignment Examples:

ExampleEdit & Run
L = ['C', 'C++', 'Java', 'Perl', 'Kotlin', 'Javascript']

L[ : 3] = ('PHP', 'Html', 'CSS')
print( L )

L[-3: ] = ['Javascript', 'Jquery', 'Bootstrap']
print( L )
copy
Output:
['PHP', 'Html', 'CSS', 'Perl', 'Kotlin', 'Javascript'] ['PHP', 'Html', 'CSS', 'Javascript', 'Jquery', 'Bootstrap'] [Finished in 0.009590956382453442s]

Trying to assign on an invalid index or slice will raise an  IndexError.

ExampleEdit & Run
L =['C', 'C++', 'Java', 'Perl', 'Kotlin', 'Javascript']

L[13] = "blah" #IndexError
copy
Output:
Traceback (most recent call last):   File "<string>", line 3, in <module> IndexError: list assignment index out of range [Finished in 0.009915865026414394s]

List Methods

The list class offers a variety of practical methods that can be invoked on any list instance. Let us look at some of these methods.

append()

Syntax:

L.append(item)
copy

This method is used to add an item to the end of the list.

ExampleEdit & Run
L = [1, 2, 3, 4]
L.append(5)
print( L )

L2 = ['C', 'C++', 'Java', 'C#']
L2.append('Python')
print( L2 )
copy
Output:
[1, 2, 3, 4, 5] ['C', 'C++', 'Java', 'C#', 'Python'] [Finished in 0.009878769982606173s]

clear()

Syntax:

L.clear()
copy

Removes all elements from the list, effectively making it an empty list.

ExampleEdit & Run
L = [1, 2, 3, 4, 5]

L.clear()

print( L )
copy
Output:
[] [Finished in 0.009720637928694487s]

copy()

Syntax:

L.copy()

The copy() method in creates a shallow copy of the list. This means that a new list object is created with the same elements as the original list, but any mutable elements in the original list (such as lists or dictionaries) are still referenced by both the original and the copied list. 

ExampleEdit & Run
L = [ [1, 2], [3, 4], [5, 6] ]

L2 = L.copy()
print(L2)

L[0][1] = [7]
print(L2)
copy
Output:
[[1, 2], [3, 4], [5, 6]] [[1, [7]], [3, 4], [5, 6]] [Finished in 0.010301205795258284s]

extend()

Syntax:

L.extend(iter)
copy

Adds all elements of an iterable iter (e.g. another list) to the list L.

ExampleEdit & Run
L = [1, 2, 3, 4, 5]

L.extend((6, 7, 8, 9))

print( L )
copy
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9] [Finished in 0.010287194047123194s]

index()

Syntax:

L.index(x)
copy

Returns the position (index) of the leftmost occurrence of value x in the list L, raises a ValueError if the item is not in the list.

ExampleEdit & Run
L = ['Javascript', 'C#', 'C++', 'Python', 'Java']

print( L.index('Python') )

print( L.index("Ruby") ) #ValueError
copy
Output:
3 Traceback (most recent call last):   File "<string>", line 5, in <module> ValueError: 'Ruby' is not in list [Finished in 0.009919169824570417s]

insert()

Syntax:

L.insert(i, x)

Inserts element x at position (index) i in the list L.

ExampleEdit & Run
L = [1, 2, 3, 5, 6, 7]

L.insert(3, 4)
print( L )

L2 = ['Python', 'C#', 'Java', 'PHP']
L2.insert(1, 'C++')
print( L2 )
copy
Output:
[1, 2, 3, 4, 5, 6, 7] ['Python', 'C++', 'C#', 'Java', 'PHP'] [Finished in 0.00961481872946024s]

pop()

Syntax:

L.pop(i)
copy

Removes and returns the element at index i, if i is not given it defaults to the last index of the list L .

ExampleEdit & Run
L = ['python', 'C++', 'Java', 'Ruby', 'Kotlin', 'C#', 'Javascript']

print( L.pop() ) #removes the last element
print( L.pop(2) )

print( L ) #after poping
copy
Output:
Javascript Java ['python', 'C++', 'Ruby', 'Kotlin', 'C#'] [Finished in 0.009432273916900158s]

remove()

Syntax:

L.remove(x)
copy

Removes the leftmost occurrence of element x in the list L, raises ValueError if x is not in the list.

ExampleEdit & Run
L = ['Python', 'Ruby', 'C#', 'Javascript', 'C++','PHP']

L.remove('PHP')
L.remove('Python')
print( L )

L.remove('CSS') #ValueError
copy
Output:
['Ruby', 'C#', 'Javascript', 'C++'] Traceback (most recent call last):   File "<string>", line 7, in <module> ValueError: list.remove(x): x not in list [Finished in 0.009745186194777489s]

reverse()

Syntax:

L.reverse()
copy

Reverses the order of elements in the list L.

ExampleEdit & Run
L = [1, 2, 3, 4, 5, 6, 7]

L.reverse()

print( L )
copy
Output:
[7, 6, 5, 4, 3, 2, 1] [Finished in 0.009725579060614109s]

sort()

Syntax:

L.sort()
copy

Sorts the elements in the list L in ascending order.

ExampleEdit & Run
L = [1, 6, 2, 0, 5, 3, 4]

L.sort()

print( L )
copy
Output:
[0, 1, 2, 3, 4, 5, 6] [Finished in 0.009354795794934034s]