Robert Hemingway
Robert Hemingway

Reputation: 121

Returning multiple elements of a list

Just have a simple question I need to write a function that takes a list as a parameter and returns a new list containing all the elements of the parameter data but with the last item appearing twice.

This is what I have:

def duplicate_last(data):
    return data[:], data[-1]

So duplicate_last([1,2,3]) comes out as ([1, 2, 3], 3) but I need it in the format of [1, 2, 3, 3].

Solution?

Also can't get

   return data[:] + data[-1]

to work as "can only concatenate list (not "int") to list"

Upvotes: 1

Views: 1098

Answers (2)

Andrew Guy
Andrew Guy

Reputation: 9968

You could make a slight amendment to your current code:

def duplicate_last(data):
    return data[:] + [data[-1]]

Upvotes: 3

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18457

You want a list.

You have:

def duplicate_last(data):
    return data[:], data[-1]

That creates a tuple with two elements, a copy of the list (data[:]) and the last element of the list.

The error message is telling you exactly what the problem with data[:] + data[-1] is -- you're trying to use a list + list construction but you're doing list + int.

Solutions:

new_list = data[:]
new_list.append(data[-1])
return new_list

Or fix the TypeError directly:

return data[:] + [data[-1]]

With the extra brackets it's list + list again.

You can also do this with slicing, which always returns a list:

return data[:] + data[-1:]

Of the 3, I would probably use the last solution because it seems to me the most readable. Any of the 3 is fine, though.

Upvotes: 1

Related Questions