We also need to remember that lists are mutable, or able to be changed while the program is running. Consider the following:
data = [10,20,30,40,50]
print(data)
data[0] = 0
print(data)
Being able to store data inside a list is one thing. Accessing each element, one by one, is helpful, but there is so much more that we could do. Insider of having to build these tools ourselves, Python gives us several tools to work with the data.
Concatenating Lists
Earlier we talked about string concatenation, or the joining of two or more strings. Well, we can also concatenate lists. With that, we will add two lists together, to make one larger (i.e. longer) list made up of all of the elements of the individual lists.
list1 = [2,4,6,8]
list2 = [1,3,5,7]
list3 = list1 + list2
print(list3)
We can also use the += to concatenate a second list onto the first list, making the first list longer.
list1 = [2,4,6,8]
list2 = [1,3,5,7]
list1 += list2
print(list1)
Note: You can only concatenate a list with another list. You cannot concatenate anything else to a list.
List Slicing
Where concatenation combines two lists, slicing is the process of selecting only a portion of an existing list.
Slicing follows the general form of:
list_name[start:end]
Notice that it is very similar to working with a specific index, except now there is a colon and a second number, so you can get a range. The second number is the first item not in the list, so the following example gives you the elements “Mon” through “Fri”.
days = ['Sun','Mon','Tue','Wed','Thur','Fri','Sat']
weekdays = days[1:6]
print(weekdays)
Note: If you pick a number past a list, it will still run, but just use the last item in them list.
The in Operator
Using the in operator, you can search a list for an element. It will return a Boolean value, which means it can be used in while loops and if statements quite easily.
names = ["Jack", "Jill", "Jim", "Jane"]
if "Jim" in names :
print("We found him.")
The Del Statement
If you want to remove an element in a list, based upon it’s index, then the delete statement is the best way to go. Specify, del and then the list with the index, and you’ll remove that element.
names = ["Jack", "Jill", "Jim", "Jane"]
print(names)
# prints ["Jack", "Jill", "Jim", "Jane"]
del names[2]
print(names)
# prints ["Jack", "Jill", "Jane"]
Min and Max Functions
If you have a list of numbers, you might want to find the min and/or max value within those lists. This is fairly common if you are looking at a group of scores, dollar amounts, etc.
You could build yourself a function to loop through the list, manually determining the min and max values. However, it is easier to just use what is built into Python.
my_list = [2,4,6,8,1,3,5,7]
print("The smallest value is:", min(my_list))
print("The largest value is:", max(my_list))
Using Functions to Work with Lists was originally found on Access 2 Learn