Lists
In this lesson, we define lists, how they are used in Python and how they are different from arrays!
We'll cover the following...
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 #
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.
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 , constant time.
The insert() function
Inserts element to the list. Use it like list.insert(index, value). It works in ...