Python Question: Write a function called first. Just as in problems 6 and 7, it
ID: 3795491 • Letter: P
Question
Python Question:
Write a function called first. Just as in problems 6 and 7, it is passed a parameter x, that may or may not be a list; if is x is a list it may contain other lists. The function should return the first non-list object in x. In other words, first should return x in some cases, or x[0], x[0][0], x[0][0][0], etc.
The solution must be recursive.
For example:
>>> first(1)
1
>>> first([2,1])
2
>>> first([[3, 1], 2])
3
>>> first([[[[[[[4]]]]]], 1, 2, 3])
4
Explanation / Answer
The python function first()
# Function definition is here
def first(set1):
if isinstance(set1,list): # Checking set1 is a list or not
first(set1[0]) # if set1 is a list call first function with argument is the first element of set1
else: # this part will work if set1 is no loger a list
print set1 # hence print set1, it will be the x[0], or x[0][0] ...
return
Testing the function first()
>>> first(1)
1
>>> first(2)
2
>>> first([[2,1]])
2
>>> first([[[2],1]])
2
>>> first([[[[[[3]]]],[2],1]])
3
>>> first([[[[[[8]]]]],1,2,3])
8
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.