Thursday, June 21, 2018

Python List Exercises

There are hundreds of list exercises in Python.
Here are just a few of them.
I'm just working from web pages I found on the internet.
I intend to add to this over time.

# Print the last element on the list
# In Python, array indexes start with 0
# len[alist] prints the length
mylist = ['a', 'b', 'c', 'd']
print ("last element: ", mylist [len(mylist)-1])
last element:  d

# Find last but one in a list
# [Ummm, this is clearly harder in other languages]
mylist = ['a', 'b', 'c', 'd']
print ("last element: ", mylist [len(mylist)-2])
last element:  c

# Find the ith element of a list where the first one starts at 1
i=7
mylist = ['a', 'b', 'c', 'd','e','f', 'g', 'h', 'i', 'j', 'k']
print(mylist[i-1])
g

# Find the number of elements of a list.
mylist = ['a', 'b', 'c', 'd','e','f', 'g', 'h', 'i', 'j', 'k']
print("Number of elements in list is: ", len(mylist))
Number of elements in list is:  11

# Reverse a list.
mylist = ['a', 'b', 'c', 'd','e','f', 'g', 'h', 'i', 'j', 'k']
# this works in place so you can't print it all on the same line
mylist.reverse()
print (mylist)
['k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']


# Test if a list is a palindrome
# palindrome check - this is more convoluted than some but it helps to see the steps detailed
# Check if a given list is a palindrome
# Check indexes from 0 to the middle of the list
# Check if first index = last index, then move in by one
# Some diagnostics left in as comments

def palcheck(mylist):
 NotAPal = 0
 #print("Middle is: ",int(len(mylist)/2))
 #print ("Length of list: ", len(mylist))
 #print ("Last index: ", len(mylist)-1, "Contains: ", mylist[len(mylist)-1])
 lastindex = len(mylist)-1
 for i in range (0, int(len(mylist)/2)):
   if (mylist[i] != mylist[lastindex-i]):
     print(mylist, "is not a palindrome")
     NotAPal = 1
     break
 if (NotAPal == 0):
   print (mylist, "is a palindrome")

palcheck ([1,2,3,4,5,4,3,2,1])
palcheck ([1,2,3,4,2,3,2,1])
palcheck ([1,1,1,1])
palcheck ([1,2,3,2,1])
palcheck ([1,4,4,2,1])


[1, 2, 3, 4, 5, 4, 3, 2, 1] is a palindrome
[1, 2, 3, 4, 2, 3, 2, 1] is not a palindrome
[1, 1, 1, 1] is a palindrome
[1, 2, 3, 2, 1] is a palindrome
[1, 4, 4, 2, 1] is not a palindrome


No comments: