In: Computer Science
Write a function that will accept a list of numbers and an integer (n). The function should return a list containing every nth item from the input list, always starting with the first item in the list. The original list should not be modified.
For example, if the function is passed the list
[8, 3, 19, 26, 32, 12, 3, 7, 21, 16]
and the integer 3, it will return the list
[8, 26, 3, 16]
If the function is passed the list
[8, 3, 19, 26, 32, 12, 3, 7, 21, 16]
and the integer 4, it will return the list
[8, 32, 21]
The function should be general, and work for any list and any value of n.
The code in python is given below.
def nthElement(oldList,n): newList=[] newList.append(oldList[0]) i=n while(i < len(oldList)): newList.append((oldList[i])) i+=n return newList n1=int(input("Enter number of elements in the list: ")) inputList = list(map(int,input("\nEnter the numbers : ").strip().split()))[:n1] n=int(input("Enter the value of integer: ")) newList=nthElement(inputList,n) print(newList) The screenshot of the running code and output is given below. If the answer helped please upvote it means a lot. For any query please comment.