Reputation: 193
I want to prepend the last item of my list BinList
with a string less than or equal to
. BinList
is 10 items long.
I have prepended all the other items in my list with a string less than
using this function I wrote:
def prepend(list, string):
string += '{0}'
list = [string.format(i) for i in list]
return (list)
But I can't use this for a single item in a list.
I tried
lastbin = BinList[10]
string = 'less than or equal to '
FinalCell = string.format(lastbin)
But this just returns less than or equal to
and not the number of BinList[10]
as well.
Upvotes: 0
Views: 106
Reputation: 19776
def prepend(list, string, last_string):
list[:-1] = [(string + str(i)) for i in list[:-1]]
list[-1] = last_string + str(list[-1])
return list
prepend([1, 2, 'tank'], 'less than ', 'less than or equal to ')
# ['less than 1', 'less than 2', 'less than or equal to tank']
list[:-1] = [1, 2]
(exclude last item)list[:-1] =
, see list slicing vs assignmentUpvotes: 1
Reputation: 27485
No need to loop or anything just use slicing like your second example but simple assign in the same line. Also BinList[-1] will access the last elemnt in the list:
BinList[-1] = 'less than or equal to {}'.format(BinList[-1])
You can even make prepend treat the last element in the list apart from the others:
BinList = [1, 2, 3]
def prepend(l, string, last):
length = len(l)
return [[last, string][i<length-1].format(s) for i, s in enumerate(l)]
print(prepend(BinList, 'equal to {}', 'less than or equal to {}'))
This returns:
['equal to 1', 'equal to 2', 'less than or equalto 3']
Upvotes: 1