Lists are Python data structures similar to arrays in other languages
part of #100DaysofCode Python Edition follow along at https://jcutrer.com/100daysofcode
Python Docs Reference: https://docs.python.org/3/tutorial/datastructures.html
A list is written as comma-separated values (items) between square brackets.
["stop", "start", "restart"]
Lists can contain items of different types - more about lists here https://docs.python.org/3.7/tutorial/introduction.html#lists
Let's create two lists, a list of numbers & a list of strings
mylist = [10,20,30,40,50,60,70,80,100]
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
mylist
days
len()
works as expected on a list
len(mylist)
Lists can contain mixed types
person = ["John", "Doe", 23, "Texas", 73301, 30.21970, -97.74726]
print(type(person))
print(person)
print()
for i in person:
print(type(i), i)
Access values in a list by index
person[0] # get first item
Negative index start from the end of the list
person[-1] # get last item
Accessing an index out of range raises an IndexError
person[10]
We can use try:
to test for this error
If this syntax is confusing, we will cover exception handling in further detail later.
try:
person[10]
except:
print("An exception occurred")
The specific exception is IndexError
, we can catch that specific error like this.
try:
person[10]
except IndexError:
print("Oops! That was no valid index. Try again...")
except:
print("Something else went wrong")
Access a range of values in a list using slicing
person[:2] # returns list of first and last name
List slicing with Negative indexes
person[-2:] # get only last two items (lat long)
.append()
adds items to the end of a list
person.append('Male')
person
.insert()
adds item to the beginning of a list
person.insert(0, 'Mr')
person
You can use the +
operator to combine two lists and return a list
colors = ['red', 'green', 'blue']
more_colors = ['yellow', 'purple', 'orange']
all_colors = colors + more_colors
print(colors)
print(more_colors)
print(all_colors)
.extend()
will also combine lists but it is performed inplace on the first list
colors.extend(more_colors)
colors
.pop
removes an item from the end of the list and returns it.
colors.pop() # last item in list is return and removed
printing the list again proves that yellow was indeed removed
colors
.sort()
will alpha sort the list but not return anything
colors.sort()
colors
reverse sorting
colors.sort(reverse=True)
colors
Sorting without modifiying the original list
colors = ['red', 'green', 'blue', 'yellow', 'purple', 'orange']
sorted_colors = sorted(colors) # sorted returns a new list and does not modify colors
print(colors)
print(sorted_colors)
Some data to start with
nums = [12, 43, 54, 64, 11, 34, 22, 5, 8]
Find the min value
min(nums)
Find the max value
max(nums)
Find the sum of all values
sum(nums)
Find the average
avg = sum(nums)/len(nums)
avg
A list of names
names = ['Bob', 'Jane', 'Susan', 'Fred', 'John', 'Mark', 'Mary']
Testing if a value in a list using the in
keyword
'Mary' in names
Testing for a value in list as part of an if
statement
if 'John' in names:
print('John is present')
Testing if value is not in a list
if 'Frank' not in names:
print('Frank is not present')
Search with .index()
names.index('Jane') # returns index of item in list
Flatten a list into a comma seperated string
names_str = ', '.join(names)
names_str
Convert from comma seperated string back to a list
new_names = names_str.split(', ')
new_names
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
for day in days:
print(day)
To add a little humor lets print only days that end in y
for day in days:
if day[-1] == 'y':
print(day)
Lets do that again but with months
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']
for month in months:
if month[-1] == 'y':
print(month)
"Shifting gear a bit, let's build a function"
This function will looped through the passed (first argument) list and build and return a new list that ends with the passed letter (second argument).
def ends_in(target_list, letter):
new_list = []
for i in target_list:
if i[-1] == letter:
new_list.append(i)
return new_list
# months that end in y
print(ends_in(months, 'y'))
# months that end in r
print(ends_in(months, 'r'))
list assignment does not copy a list, it assigns the new variable a pointer to the same list in memory
list1 = [1,2,3,4,5,6,7]
list2 = list1
# remove an item from list1
list1.pop()
# add an item to list2
list2.append(8)
# as you can see, list1 and list2 are pointers to the same list in memory.
print(list1)
print(list2)
We can use the .copy()
method to properly copy a list
list2 = list1.copy()
list1[0]= -1
list2.pop()
print(list1)
print(list2)
List slicing is another way to copy python lists
list2 = list1[:]
print(list2)
According to this stackoverflow question there are more pythonic was to copy a list.
See: https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list
Copy a list using the list()
method
old_list = [1,2,3]
new_list = list(old_list)
You can use generic copy.copy():
import copy
new_list = copy.copy(old_list)
If the list includes nested lists or other data structures you should always us copy.deepcody()
import copy
new_list = copy.deepcopy(old_list)
Near the top of this notebook we learned the lists can contain multiple types of items. Lists can also include nested lists and even other data structures such as sets, tuples, and dictionaries.
A list of lists
nested_list = [ [1,2,3], [4,5,6], [7,8,9]]
print(nested_list)
Here is how we can access the items in our nested list.
print(nested_list[0][1])
print(nested_list[2][0])
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
for index,day in enumerate(weekdays):
print( f'Item at weekday[{index}] is {day}')
This notebook is part of my #100DaysofCode Python Edition project.