This two part series will provide an introduction to using lists and how to work with them in python, from traversing a for loop to using map() and list comprehension strategies.
Lists
A list in python is a collection of various elements. A list can be a collection of integers, characters, dictionaries, or all of the above, not to be confused with an array. An array requires all elements to be of the same type.
# Empty List
empty_list = []
# List of integers
number_list = [1, 2, 3, 4, 5]
# List of strings
alpha_list = ["alpha", "beta", "charlie", "delta", "echo"]
# List of dictionaries
dict_list = [{"id": 1, "role": "admin"}, {"id": 2, "role": "manager"}]
# List of mixed value types
mixed_list = [1, "two", 3, False]
# check the type
type(number_list)
# OUTPUT: <class 'list'>
Index & Length
# Access list items by a positive index
alpha_list[1]
# OUTPUT: 'beta'
# Negative index can also be used to access list elements
number_list[-2]
# OUTPUT: 4
# Length of the list
len(alpha_list)
# OUTPUT: 5
Slicing
Using indexes, access a subset of a list by using two indexes seperated by a colon [x:y]
, x element is inclusive, y element is not. Omitting the first index, the slice starts at index 0. Omitting the second index, the slice continues until the end of the string.
number_list[1:3]
# OUTPUT: [2, 3]
number_list[:4]
# OUTPUT: [1, 2, 3, 4]
number_list[2:]
# OUTPUT: [3, 4, 5]
# Negative indexes with slicing can also be used
number_list[-3:]
# OUTPUT: [3, 4, 5]
number_list[:-3]
# OUTPUT: [1, 2]
Join & Split
String variables can be split into a list. Default delimiter is a space but a character delimeter can be specified.
"Hello world".split()
# OUTPUT: ['Hello', 'world']
"Hello world".split('o')
# OUTPUT: ['Hell', ' w', 'rld']
# The Join method does the opposite and combines a list into a string
" ".join(['Hello', 'world'])
# OUTPUT: 'Hello world'
"-".join(['Hello', 'world'])
# OUTPUT: 'Hello-world'
Mutable
Lists are mutable.
# Add elements by appending to the end of the list
alpha_list = ["alpha", "beta"]
alpha_list.append("charlie")
alpha_list
# OUTPUT: ['alpha', 'beta', 'charlie']
#Insert elements at a specific index
alpha_list.insert(0, "delta")
alpha_list
#OUTPUT; ['delta', 'alpha', 'beta', 'charlie']
Remove/ Delete
Elements can also be removed/deleted from the list.
# del will remove the element at a specific index
del alpha_list[3]
alpha_list
#OUTPUT; ['delta', 'alpha', 'beta']
# Remove will remove the first match in the list
# If multiple matches exist in the list, not all elements are removed
alpha_list.remove('alpha')
alpha_list
#OUTPUT; ['delta', 'beta']
Other Helper Methods
# Reverse the order of the list
alpha_list = ["alpha", "beta"]
alpha_list.reverse()
alpha_list
# OUTPUT: ['beta', 'alpha']
# Sort the list
alpha_list.sort()
alpha_list
# OUTPUT; ['delta', 'beta']
For Loop
# Create a List of grades
grades = [90, 80, 95, 100, 75]
# Iterate over the list and print each individual grade
for i in grades:
print(i)
# OUTPUT:
# 90
# 80
# 95
# 100
# 75
# Show indexes for elements in list using the enumerate function in a for loop
alpha_list = ["alpha", "beta", "charlie"]
for index, alpha in enumerate(alpha_list):
print(f"The word at index: {index} is {alpha} ")
# OUTPUT:
# The word at index: 0 is alpha
# The word at index: 1 is beta
# The word at index: 2 is charlie
Part 2 of this series will include the more functional programming concepts such as map() and list comprehension examples.