1

I want to add c times b integer to middle of the list. Here my code:

listA.insert(int(len(listA)/2),b*c)
print("Your New List: ", listA)

When I change (b*c) to ([b]*c) it works but I will convert it integer later. Therefore, it must be formal form like [1,2,3,4,5] not [1,2,[3],4,5]. If we say listA = [1,2,3,4,5] and let's suppose b = 2 and c = 3 I need to have [1,2,2,2,2,3,4,5]. Also, I don't have permission to use loop.

martineau
  • 119,623
  • 25
  • 170
  • 301
CrowMasteR
  • 13
  • 4
  • If you read the [Python documentation](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists), you would see that it says the `insert` function "Insert an item at a given position". So it can only put a single element there. – Zack Light Nov 07 '21 at 06:54

2 Answers2

2

Use list slicing:

lst = [1,2,3]
middle = len(lst) // 2
lst[middle:middle] = [2] * 10

Output:

[1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3]
Pedro Maia
  • 2,666
  • 1
  • 5
  • 20
0

b * c will return an integer value. So that will not work.

You can use array slice and concat to do this.

listA = listA[0 : len(listA)//2] + [2] * 3 + listA[len(listA)//2 : len(listA)]

Edit:

As per the OPs comment, this array needs to be converted to a single integer. It can be done as follows:

result = int("".join([str(number) for number in listA]))

If I put it all together

listA = [1, 2, 3, 4, 5]
listA = listA[0 : len(listA)//2] + [2] * 3 + listA[len(listA)//2 : len(listA)]
print(listA)
result = int("".join([str(number) for number in listA]))
print(result)

Following is the output:

[1, 2, 2, 2, 2, 3, 4, 5]
12222345
ThisaruG
  • 3,222
  • 7
  • 38
  • 60
  • It works but after adding new elements, As I said I need to convert the list into integer. I mean if list [1,2,3,4], I will make it 1234. Therefore, your method cannot be converted in my code. – CrowMasteR Nov 07 '21 at 07:17
  • It does. You just have to do this: ```int("".join([str(number) for number in listA]))``` – ThisaruG Nov 08 '21 at 05:14