More on Lists
We have discussed the basics of List data type and now, we will talk a little about more advanced concepts. Don't worry! These are more interesting than being 'advanced'!
Negative Index
REMINDER: Index in a list starts from 0.
We have learnt how to use the index to call an item in any list.
>>> data = [1, 2, 3]
>>> data[2]
3
We also saw how it gives an out of range error if the range is larger than the number of items present.
>>> data[3]
Traceback (most recent call last):
File "python", line 1, in <module>
IndexError: list index out of range
Now, what if the entered index is a negative number? Will it show an error or not? Is it a legal command in Python?
>>> data[-1]
Turns out, this is a completely legal command. The items start from the index 0 and go on to the number of the objects they have (excluding the last number, as it starts from 0). When we use a negative number, it starts from the last item. So in the above example, 3
is mapped to index -1, 2
is mapped to index -2 and 1
is mapped to index -3
. If we go further into the negative numbers, we will get the same error as above example, IndexError
.
The output should be:
>>> data[-1]
3
Lets try a more interactive example:
>>> print("I have "+ str(data[-1]) + " apples!")
I have 3 apples!
Sublists
Indexes, as we read, are used to get a single value from a list. What if we want multiple values? Do we need to call the function multiple times with different indexes? Python helps you with this! Slices help us do this in the form of a new list. The only difference is, slices have more than one argument seperated by colon (:).
>>> data = ['apple', 'berry', 'cherry', 'durian']
>>> data[2]
'cherry'
>>> data[0:2] # -> Slicing the list
['apple', 'berry']
Lets explain this further. The slice starts from the first index and ends at the second index (excluding the item at that index). Hence, data[0:2]
printed only ['apple', 'berry']
.
We will now introduce a third index, that controls the number of values you want to skip before using the next one in the list.
>>> numberList = [1,2,3,4,5,6,7,8,9,10]
>>> numberList[0:10:2]
[1, 3, 5, 7, 9]
In this example, we start from index 0
and go forward 2 steps to 3
as the third index in the list is 2
. This might be a bit confusing at first, but if you look at it carefully, it all adds up. The first index is the start point, second index is the non-inclusive end point and third index helps you with the number of steps you wish to take.
One more thing about sublists, the case where we input only one index in the list and leave the other one or two blank.
>>> numberList = [1,2,3,4,5,6,7,8,9,10]
>>> numberList[:2]
[1, 2]
>>> numberList[:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numberList[2:]
[3, 4, 5, 6, 7, 8, 9, 10]
As we can see, this is also the same concept.
- For
numberList[:2]
, every number before index2
was printed. - As
numberList[:]
did not have a bound, the entire list was printed. - In this case
numberList[2:]
, all numbers starting from index2
were printed.
Using the len()
function
This one's a short section. You can guess it from the topic headline. One main task is to find out the length of the list, for various operations like running a loop over it. We will first figure out how to find the length and then talk about loops.
>>> numberList = [1,2,3,4,5,6,7,8,9,10]
>>> len(numberList)
10
We use the len()
function to calculate the length of a String or List, from the concepts we have learnt so far.
Concatenation and Replication of Lists
Concatenation, as we have discussed earlier, refers to adding two or more lists. We use the +
operator for it. Replication means replicating the list in another or the same variable multiple times. We use the *
operator for it.
>>> newList = [1,2,3]
>>> data = ['apple', 'berry', 'cherry']
>>> newList + data # -> concatenation
[1, 2, 3, 'apple', 'berry', 'cherry']
>>> newList * 3 # -> replication
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> data = [4, 5, 6]
>>> newList + data
[1, 2, 3, 4, 5, 6]
Modifying item values inside the list using Indexes
Usually a variable name is on the left side of an assignment statment, like data = 10
. Python allows us to use an index of a list to change the value at that index.
>>> newList = [1,2,3]
>>> newList[1] = 'New Value'
>>> newList
[1, 'New Value', 3]
>>> newList[1] = newList[2]
>>> newList
[1, 3, 3]
Deleting an item from the list
Now that we know how to create, concatenate, replicate and find the length of a list, lets find out how to delete an item in the list. We use the del
keyword for this. All of the values in the list after the deleted value will be moved up one index.
>>> newList = [1,2,3]
>>> del newList[1]
>>> newList
[1,3]
The del
statement can be used to delete simple variables as well. If we use the deleted variable again, then there will be a NameError
because the variable no longer exists.
IMPORTANT: In practice, we almost never need to delete simple variables. The
del
statement is mostly used to delete values from lists.