All you need to know about Python Lists
Kedar Kodgire
Posted on April 1, 2020
What's a list?
It's one of the data structures in python. The lists are flexible and very easy to work with as they are mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item.
Creating a List
A list is created by placing all the items (elements) inside a square bracket [ ], separated by commas. It can also be created with list()
function.
It can have any number of items and they may be of different types (integer, float, string, etc.). YOu can also have lists inside lists i.e. nested lists.
# empty list
new_list = []
# another way
another_list = list()
# list of integers
integer_list = [1, 2, 3]
# list with mixed datatypes
mixed_list = [1, "Hello", 3.4]
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
Accessing elements from the list
We can use []
to access an item in a list. The index starts from 0. So, a list having 5 elements will have an index from 0 to 4. The index must be an integer. We can't use float or other types, this will result in TypeError
. Trying to access an element other that this will raise an IndexError
.
>>> y = ['d', 'f', 's', 'd', 'f', 's', 'd', 'f']
>>> y[0]
'd'
# Nested List
>>> n_list = ["Happy", [2,0,1,5]]
>>> n_list[0][1]
'a'
>>> n_list[1][3]
5
Negetive Indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.
>>> y = ['d', 'f', 's', 'd', 'f', 's', 'd', 'f']
>>> y[-1]
'f'
slicing in Lists
This is one of the interesting and easy ways of accessing a range of items in a list by using the slicing operator (colon). Let's look at some examples
>>> y = ['d', 'f', 's', 'd', 'f', 's', 'd', 'f']
>>> y[2:5]
['s', 'd', 'f']
>>> y[:] #getting complete list
['d', 'f', 's', 'd', 'f', 's', 'd', 'f']
>>> y[4:] #index 4 to end
['f', 's', 'd', 'f']
>>> y[:4] # from beginning to index 3
['d', 'f', 's', 'd']
>>> y[:-5]
['d', 'f', 's']
Removing elements from the list
We can use the del
keyword to remove an item at the given index.
the clear() method can also be used to empty a list.
let's look at some examples
>>> y = ['d', 'f', 's', 'd', 'f', 's', 'd', 'f']
>>> del y[0]
>>> y
['f', 's', 'd', 'f', 's', 'd', 'f']
>>> del y[1:3] #deleting multiple items
>>> del y # deleting list
Adding or changing list items
We can use the assignment operator (=) to change an item or a range of items.
>>> y = ['d', 'f', 's', 'd', 'f', 's', 'd', 'f']
>>> y[0] = 'd'
>>> y
['d', 's', 'd', 'f', 's', 'd', 'f']
We can use +
operator to join two lists, *
repeating list for a given number of times and we can insert one item at a desired location by using the method insert()
or insert multiple items by squeezing it into an empty slice of a list.
>>>odd = [1, 3, 5]
>>> odd + [9, 7, 5]
[1, 3, 5, 9, 7, 5]
>>> ["list"] * 3
["list", "list", "list"]
>>>odd.insert(1,4)
>>> odd
[1, 4, 3, 5]
List Comprehension
List comprehension is an elegant and concise way to create a new list from an existing list in Python. List comprehension consists of an expression followed by for statement inside square brackets.
Let's look at an example where we need to triple value of each element in the list
>>> [3 ** x for x in range(10)]
[1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683]
This is equivalent to
three = []
for x in range(10):
three.append(3 ** x)
we can also use multiple for loops in it.
List methods
- copy()
The copy method returns a shallow copy of the list. We can also copy one list into another like this
>>> y = ['d', 'f', 's', 'd', 'f', 's', 'd', 'f']
>>> x = y
>>> x
['d', 'f', 's', 'd', 'f', 's', 'd', 'f']
The problem with this way of copying list is if you modify one list then another will also get modified. Hence, in this case, we use copy.
>>> list = ['cat', 0, 6.7]
>>> new_list = list.copy()
>>> new_list.append('dog')
>>> list
['cat', 0, 6.7]
>>> new_list
['cat', 0, 6.7, 'dog']
- remove()
The remove()
method removes the first matching element (which is passed as an argument) from the list.
It takes a single element as an argument and removes it from the list. If the element doesn't exist, it throws ValueError: list.remove(x): x not in list exception
. Let's look at an example.
>>> animals = ['cat', 'dog', 'rabbit', 'guinea pig']
>>> animals.remove('rabbit')
>>> animals
['cat', 'dog', 'guinea pig']
>>> animals = ['cat', 'dog', 'rabbit', 'rabbit', 'guinea pig']
>>> animals.remove('rabbit')
>>> animals
['cat', 'dog', 'rabbit', 'guinea pig']
- append()
The append()
method adds a single item to the end of the list. The item can be numbers, strings, dictionaries, another list, and so on.
>>> animals = ['cat', 'dog', 'rabbit']
>>> wild_animals = ['tiger', 'fox']
>>> animals.append(wild_animals)
>>> animals
['cat', 'dog', 'rabbit', ['tiger', 'fox']]
- extend()
The extend() extends the list by adding all items of a list (passed as an argument) to the end.
>>> animals = ['cat', 'dog', 'rabbit']
>>> wild_animals = ['tiger', 'fox']
>>> animals.extend(wild_animals)
>>> animals
['cat', 'dog', 'rabbit', 'tiger', 'fox']
similarly, If you need to add elements of other data types (like tuple and set) to the list, you can simply use:
list.extend(list(tuple_type))
- count()
The count()
method returns the number of times the element in the specified list. Let's have a look at an example
>>> nums = [1, 4, 2, 9, 7, 8, 9, 3, 1]
>>> x = nums.count(9)
>>> x
2
- index()
The index() method searches an element in the list and returns its index. If the same element is present more than once, the method returns the index of the first occurrence of the element.
>>> vowels = ['a', 'e', 'i', 'o', 'i', 'u']
>>> index = vowels.index('e')
>>> index
1
- len()
The len() function returns the number of items (length) in an object. An object can be (string, bytes, tuple, list, or range) or a collection (dictionary, set or frozen set)
>>> testString = 'Python'
>>> len(testString)
6
>>> vowels = ['a', 'e', 'i', 'o', 'i', 'u']
>>> len(vowels)
6
- pop()
The pop() method removes the item at the given index from the list and returns the removed item. The argument passed to the method is optional. If not passed, the default index -1 is passed as an argument (index of the last item). This helps us implement lists as stacks (first in, last out data structure).
>>> languages = ['Python', 'Java', 'C++', 'French', 'C']
>>> languages.pop(3)
'French'
>>> languages
['Python', 'Java', 'C++', 'C']
- clear()
The clear() method removes all items from the list. Note that the clear()
method only empties the given list. It doesn't return any value.
>>> list = [{1, 2}, ('a'), ['1.1', '2.2']]
>>> list.clear()
>>> list
[]
- sort()
The sort() method sorts the elements of a given list in a specific order - Ascending or Descending.
By default, sort() doesn't require any extra parameters. However, it has two optional parameters:
- reverse - If true, the sorted list is reversed (or sorted in Descending order)
- key - function that serves as a key for the sort comparison
The syntax is
list.sort(key=..., reverse=...)
>>> vowels = ['e', 'a', 'u', 'o', 'i']
>>> vowels.sort()
>>> vowels
['a', 'e', 'i', 'o', 'u']
>>> vowels.sort(reverse=True)
>>> vowels
['u', 'o', 'i', 'e', 'a']
Let's have a look at key
now
>>> def takeSecond(elem):
return elem[1]
>>> random = [(2, 2), (3, 4), (4, 1), (1, 3)]
>>> random.sort(key=takeSecond)
>>> random
[(4, 1), (2, 2), (1, 3), (3, 4)]
I hope you understood this. You can also use the sorted() function, it sorts the elements of a given iterable in a specific order (either ascending or descending).
The syntax of sorted() is:
sorted(iterable, key=None, reverse=False)
iterable is a sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any other iterator.
- reverse()
The reverse() method reverses the elements of a given list. The reverse() function doesn't return any value. It only reverses the elements and updates the list.
>>> random = [(2, 2), (3, 4), (4, 1), (1, 3)]
>>> random.reverse()
>>> random
[(1, 3), (4, 1), (3, 4), (2, 2)]
- any()
The any() method returns True if any element of an iterable is True. If not, any() returns False. The any() method takes an iterable (list, string, dictionary etc.) in Python.
When | Return Value |
---|---|
All values are true | True |
All values are false | False |
One value is true (others are false) | True |
One value is false (others are true) | True |
Empty Iterable | False |
Check out the examples below
>>> l = [1, 3, 4, 0]
>>> any(l)
True
>>> l = [0, False]
>>> any(l)
False
>>> l = [0, False, 5]
>>> any(l)
True
>>> l = []
>>> any(l)
False
with strings
>>> s = '000'
>>> any(s)
True
>>> s = ''
>>> any(s)
False
- iter()
The Python iter() function returns an iterator for the given object. It creates an object which can be iterated one element at a time. These objects are useful when coupled with loops like for loop, while loop.
The syntax of the iter() function is:
iter(object, sentinel)
The iter() function takes two parameters:
- object - object whose iterator has to be created (can be sets, tuples, etc.)
- sentinel (optional) - value used to represent the end of the sequence.
Let's quickly look at the example
>>> x = iter(["apple", "banana", "cherry"])
>>> next(x)
'apple'
>>> next(x)
'banana'
>>> next(x)
'cherry'
The sentinel is used very rarely, You can find more about it here
- sum()
The sum() function adds the items of an iterable and returns the sum. The sum() function adds start and items of the given iterable from left to right.
It has two parameters
- iterable - iterable (list, tuple, etc). The items of the iterable should be numbers.
- start (optional) - this value is added to the sum of items of the iterable. The default value of start is 0 (if omitted)
>>> numbers = [1,2,3,4,5,1,4,5]
>>> sum(numbers)
25
>>> sum(numbers,25)
50
- abs()
The abs() method returns the absolute value of the given number. If the number is a complex number, abs() returns its magnitude.
- For integers - integer absolute value is returned
- For floating numbers - floating absolute value is returned
- For complex numbers - the magnitude of the number is returned
let's look at some examples
>>> integer = -20
>>> abs(integer)
20
>>> floating = -30.33
>>> abs(floating)
30.33
>>> complex = (3 - 4j)
>>> abs(complex)
5.0
enumerate()
The enumerate() method adds a count to an iterable (lists, etc) and returns it. enumerate() has two parameters
- iterable - a sequence, an iterator, or objects that supports iteration
- start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken as start.
Let's see a quick example
>>> numbers = [1,2,3,4,5,1,4,5]
>>> a = enumerate(numbers)
>>> print(list(a))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 1), (6, 4), (7, 5)]
>>> a = enumerate(numbers, 50)
>>> print(list(a))
[(50, 1), (51, 2), (52, 3), (53, 4), (54, 5), (55, 1), (56, 4), (57, 5)]
That's all folks, hope this added a little bit of value to your existing knowledge base.
other reads
Three dots "..." in JS - Spread and Rest explained
Kedar Kodgire ・ Mar 25 '20
Stuck at home, corona? Spend your time learning for free (15,000+ hours content).
Kedar Kodgire ・ Mar 27 '20
The Linux guide/cheatsheet/tutorial (Commands, Directories, etc)
Kedar Kodgire ・ Mar 21 '20
Keep in Touch
Don't forget to connect me on:
Have a great day,
Happy Learning,
and stay safe.
Posted on April 1, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.