list-data-structure-in-python

Python List Data Structure Practical Example

Last Updated | Dec, 29, 2020 By Kingsley Ijomah
In this tutorial, you'll learn about Python's List data structure. You'll look at some of the best scenarios to use it and finally, we will visit the list data structure's methods with sample codes

A list is a data structure that holds a collection of ordered mutable items. mutable means that once the list is created it can be changed, you can add more to it or remove from the list.

When to use List
Below are some reasons why you might need to use the list data structure instead.

  • You are dealing with sequenced data
  • Order might be of importance
  • Need to change the list (mutate)
  • The list is homogeneous ( same type of data )


This article is a continuation of Python Data Structures For Beginners

Let us explore lists in more details... and in the end, solve a problem using list data structure.

Topics covered in this post:

1. Creating Lists
2. List Indexing
3. How to Slice Lists in Python
4. Add Elements To a List
5. Remove or Delete List Items
6. Python List Methods
7. List Comprehension
8.List Membership Test
9. List Code Challenge

Creating Lists

code
# empty list
list = []

# list of integers
list = [1, 2, 3]

# list of strings
list = ['orange', 'apple', 'pear', 'apple', 'banana']

# list with mixed data types
list = [1, "Hello", 5.0]

List Indexing

code
# List Indexing

fruits = ['orange', 'apple', 'pear', 'apple', 'banana']


fruits[0] # Output => orange

fruits[1] # Output => apple

fruits[2] # Output => pear

fruits[3] # Output => apple

fruits[4] # Output => banana

fruits[-1] # Output => banana

fruits[-5] # Output => orange


# Nested indexing

fruits = ['orange', ['apple','orange']]

fruits[1][0] # apple

fruits[1][1] # orange

How to Slice Lists in Python

code
# List slicing in Python


fruits = ['orange', 'apple', 'pear', 'grapes', 'banana']


# beginning to end
fruits[:] # output => ['orange', 'apple', 'pear', 'grapes', 'banana']


# index 2 to 5th item
fruits[2:5] # output => ['pear', 'grapes', 'banana']


# remove last 2 items
fruits[:-2] # output => ['orange', 'apple', 'pear']


# return first 2 items
fruits[:2] # output => ['orange', 'apple']


# index 2 to the end
fruits[2:] # output => ['pear', 'grapes', 'banana']


# every nth item
fruits[::2] # output => ['orange', 'pear', 'banana']


# reverse list
fruits[::-1] # output => ['banana', 'grapes', 'pear', 'apple', 'orange']

Add Elements To a List

code
# Changing a list after it is created

fruits = ['orange', 'apple', 'pear', 'grapes', 'banana']


# change first item   
fruits[0] = 'Berries'            

print(fruits) # output => ['Berries', 'apple', 'pear', 'grapes', 'banana']


# change item in index 1 to 4th item
fruits[1:4] = ['Mandarins ','Peaches', 'Plums']  

print(fruits) # output => ['apple', 'pear', 'grapes']


# using append


fruits = ['orange', 'apple', 'pear', 'grapes', 'banana']


# add limes to end of the list
fruits.append('Limes')

print(fruits) # output => ['orange', 'apple', 'pear', 'grapes', 'banana', 'Limes']


# concatination


# adds strawberries to end of the list

fruits = fruits + ['Strawberries']

Remove or Delete List Items

code
# Deleting list items


fruits = ['orange', 'apple', 'pear', 'grapes', 'banana']


# delete nth index position
del fruits[0]


# delete the items from index position 1 to 5th item
del fruit[1:5]


# delete the entire list
del fruits

Python List Methods

append() - Adds an element at the end of the list
clear() - Removes all the elements from the list
copy() - Returns a copy of the list
count() - Returns the number of elements with the specified value
extend() - Add the elements of a list (or any iterable), to the end of the current list
index() - Returns the index of the first element with the specified value
insert() - Adds an element at the specified position
pop() - Removes the element at the specified position
remove() - Removes the first item with the specified value
reverse() - Reverses the order of the list
sort() - Sorts the list

List Comprehension

List comprehensions provide a concise way to create lists.

A list comprehension is made up of an expression followed by for statement inside square brackets.

Below is an example of creating an empty list and populating it. with squares using append.

code
# without list comprehension

squares = []
for x in range(10):
    squares.append(x**2)

print(squares) # output => [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The above will create a variable called x which still exists in memory even after the loop exits.

Using list comprehension we can achieve the same result without any side effects:

code
# with list comprehension

squares = [x**2 for x in range(10)]

print(squares) # output => [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

List Membership Test

code
fruits = ['orange', 'apple', 'pear']


# check item is in list
'orange' in fruits # output => True


# check item, not in the list
'orange' not in fruits # output => False

List Code Challenge

Hamming distance is a metric for comparing two binary data strings of equal length and returning total count where the bit positions between the two strings differ.

code
'''
There are 7 total counts where position comparison don't match
Therefore the hamming distance is 7
'''
GAGCCTACTAACGGGAT
CATCGTAATGACGGCCT
^ ^ ^  ^ ^    ^^

Below is a possible step to follow to solve this problem:

Solution Steps:

  • create variables to hold both strings as string_a and string_b
  • zip them together as a list of pairs e.g GC/AA/CC/CG ...
  • loop through the list and return non-matching pairs
  • return count of total non-matching
code
# create variables to hold both strings as string_a and string_b
string_a = 'GAGCCTACTAACGGGAT'
string_b = 'CATCGTAATGACGGCCT'

# zip them together as a list of pairs/tuples e.g GC/AA/CC/CG
zipped = zip(string_a, string_b) # => [('G', 'C'), ('A', 'A')..]

# loop through the list and return non-matching pairs
result = [[x,y] for x,y in zipped if x != y] # => [('G', 'C')]

# return count of total non-matching
len(result)

Conclusion

In the end, we did not exclusively use List, but that is not a problem, in thinking about solving this problem List data structure played the majority of the role, zip internally used Tuple to hold the pairs but it was still a list of tuples.

MY STORY

My name is Kingsley Ijomah, I am the founder of CODEHANCE, an online education platform built with you in mind, a place where I express my gratitude to a skill ( coding ) which has changed my life completely.

Learn To Code With Me.
FREE course included.

GET IN TOUCH

Enter your email address:

Delivered by FeedBurner