list data type

Introduction to list data type in python programming language

A list is the simplest data type, lists, and they implement the iterable interface, which as previously mentioned they can be used with len(), sorted() etc. In addition to being iterable, they are also “mutable sequences”, that is they store a number of arbitrary items in sequence and the list can be mutated (altered) after its creation. Due to Pythons dynamic nature you do not need to specify what the list will store, as it can store many types of objects at the same time, for example, this is perfectly valid:
>>> data = [1, 2.2, ‘three’, False, [5, 6]]
Lists can also contain lists, since lists are objects just like any other object. 
Items in a list can be accessed via index-notation, which is taking a numeric id (starting from 0) and using braces to get the value stored at the index.
For example:
Refers to the first element in the list, 1
Refers to the string element ‘three’
Python list have negative index lookup, that is you can index from negative number to start indexing from the end of the list. Where the index 0 refers to the first element in a list, the index -1 would refer to the last element in a list, -2 being the penultimate element and so on.
Would be the nested list (remembering that lists can contain lists) [5, 6].
Would contain the value False.
If we want to add an element to an existing list, we can do this with the ‘append’ function:
This will always add the element to the end of the list, if this isn’t what is needed however the insert function allows you to specify exactly where in the list to insert an element:
data.insert(0, ‘see’)
Will insert the string ‘see’ at the beginning of the list, remembering that iterable structures start from 0!
To remove an element from a point in the list, we can either use the ‘pop’ method or the ‘del’ keyword. Both methods will be shown below, however they are slightly different from one another, del will remove an item from the list whereas pop will return the element upon removal. Both del and pop require an index, but pop defaults to index 0 if one is not specified.
data.pop() # Removes the element in the 0th position
del data[0] # The same, just using del
data.pop(2) # Removes the third element in a list (0 indexed)
Where pop is concerned with removing an element at a position in a list, it might be that what’s required is that an element is to be removed without knowing its index, for those cases there’s a remove function:


However, remove will raise a Value Error if the object you are trying to remove does not exist in the list.
To determine the index of an item in a list, the unsurprisingly named index function will return the numeric index of an element, and like remove will raise a ValueError if it could not be found.
If it is required to know how many times an element appears in a list, count is the function to use:
Sorting lists has a few possible choices, the adage the right tool for the right job, if you wish to sort a list ‘in place’ that is to say permanently change the list to be ‘sorted’ you can use the list sort method. It accepts two keyword parameters, key and reverse, the reverse keyword argument is simply a Boolean that defaults to false, however the key is a parameter that expects a callable (discussed earlier in datatypes), it is not unusual to see the limited lambda functions used here as the purpose of the callable attached to the key is used to actually do the sorting.
If we consider, for simplicity’s sake, a different list, containing only strings:
>>> strings = [‘Z’, Y’, ‘X’, ‘W’]
>>> strings.sort(key=str.lower)
>>> strings
[‘W’, ‘X’, ‘Y’, ‘Z’]
Similar to the reverse keyword argument to the sort method, reverse does an in place reverse of all elements in a string.
>>> strings = [‘Z’, ‘X’, ‘Y’, ‘W’]
>>> strings.reverse()
>>> strings
[‘W’, ‘X’, ‘Y’, ‘Z’]
If you need to copy a list, you can use the copy function. It is important to understand that this returns what is known as a ‘shallow copy’, this means the copy is linked to the original and changes to the original may be reflected in the copy. Which may or may not be what you want, be mindful of the exact behavior required for a problem and ensure that the correct means to address the issue is used.
strings2 = strings.copy()
You can extend a list with another list by using the ‘extend’ function to create a composite list that puts the elements of the second list into the first.
data.extend([1, 2, 3])
You can concatenate two lists together using the + operator:
[1, 2, 3] + [4, 5, 6]
If you wish to clear the entire list there is a clear function, this will wipe all elements from the list, be aware any copies linked to this may also get wiped!.
However, one of the coolest things about lists in Python is something known as list slice notation, where you can get a subset of the elements in a list by slicing it up. Slicing has up to three aspects to it, the first is a start index and the second is an end index. To get the elements in a list (called data) between 5 and 7 the following can be done:
The slice notation is exclusive so 5:8 get elements 5, 6, and 7, but stops at 8. Something worth noting is that Lists in Python are circular, this means if you try to get the -1th element in a list, you will get the final element in the list.
All parameters in list slicing are actually optional, in fact:
[1, 2, 3, 4, 5, 6][::]
Will simply return a copy of the original list.
Slicing from only a start index, like so:
[1, 2, 3, 4, 5, 6][1:]
Will return a copy of the list starting from the 1st position, yielding the list:
[2, 3, 4, 5, 6]
Without a start index however, a start index of 0 will be assumed, which means a copy will be returned that starts from 0 and will return up to the element specified.
>>> [1, 2, 3, 4, 5, 6][:4]
[1, 2, 3, 4]
Finally, the third parameter in list slicing is a step parameter, this specifies by how many elements it should step though, it defaults to 1. In fact, the following two lines are equivalent:
>>> [1, 2, 3, 4, 5, 6][::]
>>> [1, 2, 3, 4, 5, 6][::1]
Both give a full copy of the original list, however, there’s something interesting to be seen, when one considers the significance of the fact that Python lists have the negative indexing property, a copy of the original list can be reversed with the following:
>>> [1, 2, 3, 4, 5, 6][::-1]
[6, 5, 4, 3, 2, 1]

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.