Define a function first_last(list1) that returns a list with the first and last element of list1 interchanged.
时间: 2024-02-12 07:08:06 浏览: 103
Here's the Python code for the function `first_last(list1)` that returns a list with the first and last element of `list1` interchanged:
```python
def first_last(list1):
if len(list1) < 2:
return list1
else:
first = list1[0]
last = list1[-1]
list1[0] = last
list1[-1] = first
return list1
```
This function takes in a list `list1` as its input and first checks if the length of the list is less than 2. If the length is less than 2, it simply returns the original list. Otherwise, it stores the first element of the list in a variable called `first` and the last element of the list in a variable called `last`. It then interchanges the values of `first` and `last` in the list and returns the modified list.
阅读全文