A list is an ordered collection of Python objects. As a mutable data type, lists are often used to store data that are subject to change at the runtime. Another advantageous feature of lists is that the allowance of having duplicate elements.
Because of these features, lists are probably the most used data structure in any Python project. In this article, I will share the top 5 operations for the use of Python lists with you.
1. Construction
The first apparent operation is how we create lists.
I) The easiest way will be just listing composing elements inside a pair of square brackets. We use commas to separate these items. Optionally, we can use this declaration with the * operator if we want to repeat a particular list for specific times.
Code
>>> # Create an empty list
>>> empty_list = []
>>> # A list of numbers
>>> numbers = [1, 2, 3, 4, 5]
>>> # Use * operator
>>> triples = [1, 2, 3] * 3
>>> triples
[1, 2, 3, 1, 2, 3, 1, 2, 3]
II) We can also create lists by slicing existing lists. Some examples are shown below. One quick note, these slicing operations return lists as their return values, but just to make code snippets of the present article look clear, I don’t typically assign these lists to variables such that the Python interpreter will print them automatically.
Code
>>> # Suppose we have the following list to begin with
>>> list0 = [0, 2, 4, 6, 8, 10, 12, 14]
>>> # Create a list of the same elements
>>> list0[:] # This is equivalent to list0.copy()
[0, 2, 4, 6, 8, 10, 12, 14]
>>> # Specify the start, end, and step
>>> list0[1:8:2]
[2, 6, 10, 14]
>>> # Create a list of the reverse order
>>> list0[::-1]
[14, 12, 10, 8, 6, 4, 2, 0]
III) More generally, we can use the list() function that creates lists from any iterable, such as tuples and dictionaries. When nothing is set, the list() function will create an empty list.
Code
>>> # from range
>>> list(range(4))
[0, 1, 2, 3]
>>> # from tuple
>>> list((5, 4, 3))
[5, 4, 3]
>>> # from dictionary
>>> list({'zero': 0, 'one': 1, 'two': 2})
['zero', 'one', 'two']
>>> # from map object
>>> list(map(len, ['one', 'hello', 'world!']))
[3, 5, 6]
IV) Another convenient way is to use the list comprehension. The general format is [expression for ele in iterable if condition].
Code
>>> # Create a list of squares
>>> [x*x for x in range(5)]
[0, 1, 4, 9, 16]
>>> # Create a list of even numbers
>>> [x for x in range(10) if x%2 == 0]
[0, 2, 4, 6, 8]
2. Access Elements
When we work with lists, we need to access individual elements or elements within a range.
I) We can access individual elements using indexing. Typically, we use zero-based indexing that counts from the left. Alternatively, we can use reverse indexing, which counts from the right and begins with -1.
Code
>>> numbers = [1, 4, 5, 7, 9, 13]
>>> # Forward Indexing
>>> numbers[2]
5
>>> # Reverse Indexing
>>> numbers[-1]
13
II) We can access individual and a range of elements by unpacking. It’s pretty much like unpacking a tuple (i.e., a, b = (‘code’, 404)), and we can use * and _ to have a more powerful unpacking
Code
>>> pets = ['Dog', 'Cat', 'Turtle', 'Snake', 'Hamster']
>>> # when we're only interested in the first and last element
>>> a, *_, b = pets
>>> # elements as a list and two last elements
>>> *c, d, e = pets
>>> print(f'a: {a}, b: {b}, c: {c}, d: {d}, e: {e}')
a: Dog, b: Hamster, c: ['Dog', 'Cat', 'Turtle'], d: Snake, e: Hamster
III) We can access multiple elements using slicing. It’s discussed in the above section when we use slicing to create new lists
Code
>>> numbers = list(range(20))
>>> # Get even numbers
>>> numbers[::2]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> # Get odd numbers
>>> numbers[1::2]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> # Get some numbers in the middle
>>> numbers[5:9]
[5, 6, 7, 8]
IV) We can access a random element in the list. It can be done using random.choice() function. Please note that this function is available in the random module.
Code
>>> import random
>>> lottery_tickets = ['A0049', 'A0050', 'A0051', 'A0052', 'A0053']
>>> # draw the winning ticket
>>> random.choice(lottery_tickets)
'A0050'
V) We can find the index of a particular object. To do that, we can use the index() method. Please note that we’ll encounter an error if the object isn’t on the list.
Code
>>> students = ['John', 'Mike', 'Jennifer', 'Joe']
>>> # when an object exist
>>> students.index('Mike')
1
>>> # when an object doesn't exist
>>> students.index('Mary')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'Mary' is not in list
3. Conditionals
Certain operations rely on whether a particular condition is met or not. There are multiple possible conditions that pertain to lists in Python.
I) We can check if a list is empty. When a list isn’t empty, it is evaluated as True. When it’s empty, using the not keyword will make the evaluation True. In other words, an empty list is evaluated as False.
Code
>>> some_list = [1, 2]
>>> empty_list = []
>>> if some_list:
... print('This is not an empty list')
...
This is not an empty list
>>> if not empty_list:
... print('This is to negate an empty list')
...
This is to negate an empty list
II) We can check if an element is in the list. To do that, we can use the item in the list expression. To negate it, we can use not in.
Code
>>> activities = ['soccer', 'tennis', 'swim', 'karate']
>>> # check if something is in the list
>>> 'tennis' in activities
True
>>> # check if something is not in the list
>>> 'swim' not in activities
False
III) We can check if the list contains all the elements of another list. We can take advantage of some built-in functionalities of the set datatype.
Code
>>> larger_list = [7, 8, 9, 17, 18, 19]
>>> smaller_list = [8, 9, 18, 19]
>>> # use the issuperset function
>>> set(larger_list).issuperset(set(smaller_list))
True
>>> # use the issubset function
>>> set(smaller_list).issubset(set(larger_list))
True
IV) We can check if the list contains any elements of another list. Similarly, as above, the set data type has built-in functionalities for this operation.
Code
>>> large_list = [7, 8, 9, 17, 18, 19]
>>> small_list0 = [9, 28, 29]
>>> small_list1 = [28, 29]
>>> # use the intersection function
>>> bool(set(large_list).intersection(set(small_list0)))
True
>>> bool(set(large_list).intersection(set(small_list1)))
False
4. Modify Elements
One major feature of lists is their mutability, which means we can modify their elements, such as adding and removing items.
I) We can append an element at the end or insert one at a particular index using the append() and insert() methods, respectively
Code
>>> existing_numbers = [2, 4, 6, 8]
>>> # append an element at the end
>>> existing_numbers.append(10)
>>> existing_numbers
[2, 4, 6, 8, 10]
>>> # insert an element at an index
>>> existing_numbers.insert(0, 0)
>>> existing_numbers
[0, 2, 4, 6, 8, 10]
II) We can extend the list by appending multiple elements using the extend() method, which takes in an iterable.
Code
>>> numbers_to_extend = [1, 3, 5]
>>> # extend the list with another list
>>> numbers_to_extend.extend([7, 9])
>>> numbers_to_extend
[1, 3, 5, 7, 9]
>>> # extend the list with a tuple
>>> numbers_to_extend.extend((11, 13))
>>> numbers_to_extend
[1, 3, 5, 7, 9, 11, 13]
III) We can replace certain elements directly. It can be achieved by assignment to the element at an index or elements within a range.
Code
>>> numbers_to_replace = [1, 2, 3, 5]
>>> # replace an element
>>> numbers_to_replace[3] = 4
>>> numbers_to_replace
[1, 2, 3, 4]
>>> # replace a range of elements
>>> numbers_to_replace[1:3] = [0, 0]
>>> numbers_to_replace
[1, 0, 0, 4]
IV) We can remove an element using the remove(), pop(), and del methods. The remove() method removes the matching element at its first occurrence, the pop() method removes the element at the optionally specified index, and the default index is -1 (i.e., the last one), and the del statement removes an element with its index specified. Another thing to note is that the pop() method returns the value, while the other two return None.
Code
>>> numbers_to_remove = [1, 2, 3, 4, 5, 6]
>>> # using the remove()
>>> numbers_to_remove.remove(3)
>>> numbers_to_remove
[1, 2, 4, 5, 6]
>>> # using the pop()
>>> numbers_to_remove.pop(1)
2
>>> numbers_to_remove
[1, 4, 5, 6]
>>> # using the del statement
>>> del numbers_to_remove[-1]
>>> numbers_to_remove
[1, 4, 5]
V) We can remove multiple elements using the clear() and del methods. The clear() method removes all the elements of the list, and the del statement removes multiple elements with the range specified. Another handy way to remove all elements in the list is to assign the variable with an empty list.
Code
>>> # using clear
>>> numbers_to_clear = [3, 7, 8, 9, 10]
>>> numbers_to_clear.clear()
>>> numbers_to_clear
[]
>>> # using del
>>> numbers_to_del = [3, 7, 8, 9, 10]
>>> del numbers_to_del[2:]
>>> numbers_to_del
[3, 7]
>>> # using the re-assignment; note that this doesn't actually clear the old list
>>> numbers_to_reassign = [3, 4, 5]
>>> numbers_to_reassign = []
>>> numbers_to_reassign
[]
VI) We can change the order of the list. Some common ways include sorting the list, reversing the list, and shuffling the list.
Code
>>> numbers_to_order = [7, 9, -11, 4, 0, -13]
>>> # sort the list
>>> numbers_to_order.sort()
>>> numbers_to_order
[-13, -11, 0, 4, 7, 9]
>>> numbers_to_order.sort(key=lambda x: abs(x))
>>> numbers_to_order
[0, 4, 7, 9, -11, -13]
>>> # shuffle the list
>>> import random
>>> random.shuffle(numbers_to_order)
>>> numbers_to_order
[0, 9, -11, -13, 4, 7]
>>> # reverse the list
>>> numbers_to_order[::-1]
[7, 4, -13, -11, 9, 0]
5. Iteration
It’s a prevalent task that we need to perform certain operations by going through the list’s elements, which is termed iteration.
I) We can iterate a list directly. Lists are iterables in Python, and thus we can iterate a list in a for loop directly.
Code
>>> pets = ['Dog', 'Cat', 'Bird']
>>> for pet in pets:
... print(pet)
...
Dog
Cat
Bird
II) We can iterate a list using the enumerate() function. This function allows us to track the count of the iteration. Optionally, we can set the start argument to specify the start number for the counting.
Code
>>> activities = ['soccer', 'karate', 'basketball']
>>> for i, activity in enumerate(activities, start=1):
... print(f'Day {i}: {activity}')
...
Day 1: soccer
Day 2: karate
Day 3: basketball
III) We can iterate a list using the reversed() function. This function allows us to iterate the list using the reverse order.
Code
>>> arrivals = ['John', 'Mike', 'Jennifer']
>>> for student in reversed(arrivals):
... print(student)
...
Jennifer
Mike
John
Conclusions for the 5 topics
This article summarizes the most common operations for Python lists. Here are some quick takeaways so that you can understand the topic in these 5 sentences
Hope you like it
1) We can construct lists by listing the items, using the list() function, and working with existing ones.
2) We can access individual and multiple items using indexing and ranges.
3) We can check whether the list has a particular item and its emptiness and relationship with other lists.
4) We can append, insert, and remove one or more elements. Besides, we can change the order of lists.
5) We can iterate lists using themselves and in combination with the enumerate() and reversed() functions.
Top comments (0)