– List Solutions

breakfast = ["Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"]
palindromic = ["Sausage", "Eggs", "Beans", "Beans", "Eggs", "Sausage"]
nums = [1,1,3,3,3,2,2,2,1,1,1,1,4,4,4,4]
letters = ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e']

def print_list(list):
    for item in list:
        print(item)

def last_element(list):
    return (list[-1])

def last_but_one(list):
    return (list[-2])

# Using reversed function
def my_reverse(list):
    new_list = []
    for item in reversed(list):
        new_list.append(item)
    return new_list

# Using for loop
def my_reverse2(list):
    new_list = []
    for i in range (len(list)-1, -1, -1):
        new_list.append(list[i])
    return new_list

# Using list comprehension
def my_reverse3(list): 
    return [item for item in reversed(list)] 

# Using slicing
def my_reverse4(list): 
    return list[::-1]
  
    
def is_palindrome(list):
    if list == my_reverse(list):
        return True
    else:
        return False

def compress(list):
    new_list = []
    last_item = list[0] + 1 # so first number is different to itself
    for num in list:
        if num != last_item:
            new_list.append(num)
        last_item = num
    return new_list

def pack(list):
    pack_list = []
    last_item = list[0]
    word = ""
    for item in list:
        if item == last_item:
            word = word + item
        else:
            pack_list.append(word)
            word = item
        last_item = item
    pack_list.append(word)
    return pack_list

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.