Python Essentials 1
Sorting
my_list = [8,10,6,2,4]
swapped = True
while swapped:
swapped = False
for i in range(len(my_list)-1):
if my_list[i] > my_list[i+1]:
swapped = True
my_list[i], my_list[i+1] = my_list[i+1], my_list[i]
print(my_list)
Bubble Sort - Interactive Mode
my_list = []
swapped = True
num = int(input("How many elements do you want to sort: "))
for i in range(num):
val = float(input("Enter a list element: "))
my_list.append(val)
while swapped:
swapped = False
for i in range(len(my_list) - 1):
if my_list[i] > my_list[i + 1]:
swapped = True
my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i]
print("\nSorted:")
print(my_list)
Sort Method
my_list = [8, 10, 6, 2, 4]
my_list.sort()
print(my_list)
Reverse Method
lst = [5, 3, 1, 2, 4]
print(lst)
lst.reverse()
print(lst) # outputs: [4, 2, 1, 3, 5]
Slices
# When list_1 is modified, so is list_2.
# list_1 and list_2 are references to the memory. (That is at least how I understand it...)
list_1 = [1]
list_2 = list_1
list_1[0] = 2
print(list_2)
# When list_1 is modified, list_2 is not changed in this case.
# Because list_1[:] creates a copy of list_1 and assigns it to list_2.
list_1 = [1]
list_2 = list_1[:]
list_1[0] = 2
print(list_2)
“in” and “not in”
my_list = [0, 3, 12, 8, 2]
print(5 in my_list)
print(5 not in my_list)
print(12 in my_list)
When executed, I will get the following output:
False
True
True