0

How do I insert an item into a list at a specific index? Without using:

index = 3
list = [:3] + [item] + [3:]

Help!

  • 2
    You want `list.insert`? – Ch3steR May 29 '20 at 15:36
  • I guess you meant `list = list[:3] + [item] + list[3:]`? – Tomerikoo May 29 '20 at 15:38
  • I don't want to type `list = [:3] + [item] + [3:]` all out –  May 29 '20 at 15:41
  • you can just write `lst[3:3] = [item]` – Tomerikoo May 29 '20 at 15:41
  • Who should accept as best answer? I'll go with the top one –  May 29 '20 at 15:48
  • 1
    I would say the first one... seems fair. Anyway you have here a duplicate question with 3 identical answers. That goes against the principle of this website... – Tomerikoo May 29 '20 at 15:49
  • then with Math Coder 101 or Ann Zen? –  May 29 '20 at 15:50
  • Ok Math Coder 101 was at the top so i chose him –  May 29 '20 at 15:50
  • the order of equally scored answers is random. Not willing to take anything from anybody, but @AnnZen answer is a tad better, since it is not overriding the built-in name `list` (which is an issue your original code is also presenting), and it also provides some link to the relevant official documentation. – norok2 May 29 '20 at 15:55

2 Answers2

0

Use the list.insert function:

list.insert(index, element)
AksLolCoding
  • 157
  • 10
0

You can use the insert method:

lst = ['a','b','c']
lst.insert(2,'d')
print(lst)

Output:

['a','b','d','c']
Red
  • 26,798
  • 7
  • 36
  • 58
  • 1
    Also works, and was useful. –  May 29 '20 at 15:39
  • I think it was an edit clash, sorry – norok2 May 29 '20 at 15:40
  • @Adam what do you mean *also works*? It is exactly the same as the other answer... – Tomerikoo May 29 '20 at 15:41
  • 2
    Anyway it is better to link official docs when possible and to name the code "correctly", e.g. [`list.insert()`](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists) – norok2 May 29 '20 at 15:43
  • 1
    @Tomerikoo that is true... Both answers helped –  May 29 '20 at 15:43
  • 1
    I am sure they are happy for you, but then people may perceive this as a potential conflict of interest, and perhaps you should also disclose your affiliation status. – norok2 May 29 '20 at 15:46
  • @norok2 when you print(lst.insert), you get "", which is what I said, it's a method. – Red May 29 '20 at 15:47
  • 1
    Sure, but surrounding it with apices signals others that it is actual code, not just a word. Then, if it is a method, it is a method of a class, so why not writing the name of the class directly? Finally, people not familiar with OOP nomenclature may find easier to associate it to a callable if you also include parentheses. – norok2 May 29 '20 at 15:51
  • @AnnZen It means that I assume that whoever wrote the website you mentioned is happy that you appreciate their work. – norok2 May 29 '20 at 15:56