Lists

In this lesson, we define lists, how they are used in Python and how they are different from arrays!

In Python, a list is an ordered sequence of heterogeneous elements. In other words, a list can hold elements with different data types. For example,

list = ['a', 'apple', 23, 3.14] 

Initializing a list #

Press + to interact
example_list = [3.14159, 'apple', 23] # Create a list of elements
empty_list = [] # Create an empty list
sequence_list = list(range(10)) # Create a list of first 10 whole numbers
print(example_list)
print(empty_list)
print(sequence_list)

So lists can hold integers, strings, characters, functions, and pretty much any other data type including other lists simultaneously! Look at the following example. another_list contains two lists, a string, and a function! The elements can be accessed or ‘indexed’ using square brackets. The first element in a list is accessed using index 0 (as on line 7), the second element is accessed using 1, and so on. So list indices start at 0.

Press + to interact
a_list = [2, 'Educative', 'A']
def foo():
print('Hello from foo()!')
another_list = [a_list, 'Python', foo, ['yet another list']]
print(another_list[0]) # Elements of 'aList'
print(another_list[0][1]) # Second element of 'aList'
print(another_list[1]) # 'Python'
print(another_list[3]) # 'yet another list'
# You can also invoke the functions inside a list!
another_list[2]() # 'Hello from foo()!'

Important list functions

Let’s have a look at some useful built-in Python list functions. The time complexity of each of these operations is the asymptotic average case taken from the Python Wiki page. A word of caution though: don’t use these to replace your interview answers. For example, if you are asked to sort an array/list, don’t simply use the list sort() function to answer that question!

The append() function

Use this function to add a single element to the end of a list. This function works in O(1)O(1), constant time.

Press + to interact
list = [1, 3, 5, 'seven']
print(list)
list.append(9)
print(list)

The insert() function

Inserts element to the list. Use it like list.insert(index, value). It works in O(n ...