0

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.

wilberox
  • 193
  • 10
  • What is the length of BinList? – Alex_P Sep 30 '19 at 19:32
  • 1
    Doesn't there need to be `{}` in the format string? `string = 'less than or equal to {}'` – 001 Sep 30 '19 at 19:33
  • you are not using `format` correctly. `'less than or equal to {}'.format(lastbin[-1])` – mad_ Sep 30 '19 at 19:35
  • You're probably not approaching this the right way. Why are you just appending/prepending a string like that to every element on the list? If this is going to be shown as some kind of output, just do it there. You typically don't want to store formatting info into a data structure – NullUserException Sep 30 '19 at 19:37
  • `BinList` is 10 items long – wilberox Sep 30 '19 at 19:42

2 Answers2

1

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']
Jab
  • 26,853
  • 21
  • 75
  • 114
1
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']
OverLordGoldDragon
  • 1
  • 9
  • 53
  • 101