# Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) # and makes a new list of only the first and last elements of the given list. # For practice, write this code inside a function. import random def mainstart(): testing = int(input("Enter the length of the array: ")) input_array(testing) def input_array(testing): a = [random.randint(0, 100) for i in range(testing)] print("Array: " + str(a)) # take_array(a) printfirstandlast(testing, a) def printfirstandlast(testing, a): c = [] for i in range(testing): b = a[0] c.append(b) b = a[-1] c.append(b) break print(c) mainstart()
Lessons Learned:
- I need to start practicing regularly. I’m forgetting what I’m learning.
- If you slice a list and append it, then list of list will be formed and not a simple one. [[num1], [num2]] – Wrong
Instead [num1, num2] – Correct - I was getting continuous error on runtime when I tried running the code only to realise that my last function printfirstandlast I was passing the incorrect variable. So in short when I had to pass two variables, I was only passing one (only the array) and even in my range function I had passed the incorrect variable (the array instead of the length).
Good job on your python adventure! Happy coding!
LikeLike