Reputation: 59
I have to write a code that will switch the first item in a tuple with the last one, unless there is only one item. I understand in tuples this cannot be done, but it can be done in a list. So in my code I am changing the tuple to be a list. after running the code it should look like this:
>>>switchItems((6,4,8,3,7,9,4))
(4,4,8,3,7,9,6)
>>>switchItems((“hi” , 23))
(23, “hi”)
>>>switchItems((89,))
(89,)
My code doesn't do this. It returns a list in between and I don't really know how to make it work properly, this is my code:
switchItems(tuple):
new = list(tuple)
return new[-1],new [1:-2],new[0]
And it returns this:
>>>switchItems((6,4,8,3,7,9,4))
(4, [4, 8, 3, 7], 6)'
Upvotes: 2
Views: 1056
Reputation: 1028
If you just need a copy of switched tuple. (Certainly you won't get it in place)
def switchItems(t):
if len(t) > 1:
return tuple(t[-1] + list(t[1:-2]) + t[0])
return t
Upvotes: 0
Reputation: 10493
This is one way to fix your code.
def switchItems(tup):
if len(tup) > 1:
new = list(tup)
new[0], new[-1] = new[-1], new[0]
return tuple(new)
return tup
Length check helps avoid possible errors and needles tuple
to list
to tuple
conversion.
Now, let's talk a bit about your problems.
The function switchItems was not properly defined. In Python you are supposed to use def
(or lambda
) to define a function, but I'm sure that is an artifact of copy-pasting.
You shouldn't use argument names that shadow built-in names, i.e. don't use tuple
as an argument name.
According to PEP8 you should avoid using CamelCase to name functions in Python, e.g. switchItems
should be switch_items
. This is not enforced, but highly appreciated.
Upvotes: 4
Reputation: 180391
The length does not matter, you just have to swap the first and last elements:
def switch_items(t): # use lowercase and underscores for function names
t = list(t)
t[0],t[-1] = t[-1],t[0]
return tuple(t)
You would maybe want to catch an empty tuple though:
Or slice and check the len:
def switch_items(t):
return t[-1:] + t[1:-1] + t[0:1] if len(t) > 1 else t
Upvotes: 4
Reputation: 47846
You can do the following:
def switchItems(my_tuple):
l1 = list(my_tuple) # Convert to a list
if l1: # check if not empty to prevent 'list index out of range' error
l1[0], l1[-1] = l1[-1], l1[0] #swap first and last items
return tuple(l1)
You pass the tuple to switchItems()
function. The function converts the tuple to a list. It then swaps the first and last element using indices 0
and -1
if list obtained in previous step was not empty. This is done to prevent list index out of range
error on accessing first and last element.
Upvotes: 0