List Warm-Ups

Swap First and Second

Write a function called swappy:

print(swappy(['a', 'b', 'c']))
#  prints ['b', 'c', 'a']

Swap First and Second

Here's one way to do it…

def swappy(my_list):
	# create a copy of the original list
	new_list = my_list[:]
	if len(new_list) >= 2:
		new_list[0], new_list[1] = new_list[1], new_list[0]
    return new_list

An Average Point

Write a function called average_point:

print(average_point([[2, 2], [3, 1], [4, 0]]))
#  prints out [3.0, 1.0]

An Average Point Solution

Nested lists can be tricky sometimes, but here's a solution that could work:

def average_point(points):
	x_total = 0
	y_total = 0
	for p in points:
		x_total += p[0]
		y_total += p[1]
	return [x_total / len(points), y_total / len(points)]
	

All Y

Using the same list of points (a list of lists) as the previous example, write a function called all_y:

print(all_y([[2, 200], [3, 1], [4, 9]])) # --> [[2, 200], [4, 99]]
def all_y(points):
	new_points = []
	for point in points:
		if point[1] > point[0]:
			new_points.append(point)
	return new_points

Sorting an List Without Sort!

  1. go through each position in the list and look at that element
  2. compare the value of the current element with the value of the next element
  3. if the value of the current element goes after the value of th next element, swap elements
  4. remember, the idiomatic way of swapping in python is a, b = b, a
  5. of course, once you're at the last element, there's no next element to check
  6. once you've gone through all of the elements… REPEAT the whole process if you've swapped at least once