Insert question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Insert question

words=["a","b","c"] Can I insert more than one item into words without writing so many words.insert()?

6th Feb 2017, 1:08 PM
C.R.Devila
C.R.Devila - avatar
3 Answers
+ 3
You can use + to add single items or whole lists to an existing list. I've written an example for you: words = ["a","b","c"] more_words = ["d","e","f"] best_words = words + more_words + ["g"] print (best_words) for char in "hijk": best_words += [char] print (best_words) If you run it, you'll see, that it will print a list containing all letters from "a" to "g" or "k" respectively.
6th Feb 2017, 2:19 PM
Tob
Tob - avatar
+ 3
One way to do it would be to just add them to a big list and use sort(). You can specify a key function if necessary. Whether this is more efficient than repeated insertion will depend on your data though.
6th Feb 2017, 3:25 PM
Tob
Tob - avatar
+ 1
@Tobi So I can only write each list separately and than add them? What if I want to add more than one item into different positions?Like add 2&5 into[1,3,4,6] and make it [1,2,3,4,5,6]
6th Feb 2017, 2:29 PM
C.R.Devila
C.R.Devila - avatar