+ 1

Lists

If I create a list and, let's say, I want to add a few more integers in the list, how should I do that? For eg: a="Babu" a=list(a) now let's say I want to insert the integer 3 in the list. How do I do that?

8th Jul 2017, 7:41 AM
Arpan Sircar
Arpan Sircar - avatar
3 Answers
+ 7
There are actually 3 methods of adding elements to a list: list.append(elem) -- adds a single element to the end of the list. Common error: does not return the new list, just modifies the original. list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right. list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend(). a = "Babu" a = list(a) print(a) ['B', 'a', 'b', 'u'] a.insert(1,"X") print(a) ['B', 'X', 'a', 'b', 'u'] a.extend(["L", "M", "N"]) print(a) ['B', 'X', 'a', 'b', 'u', 'L', 'M', 'N']
8th Jul 2017, 10:07 AM
Maya
Maya - avatar
+ 5
a.append(3) this will add the number 3 at the end of your list
8th Jul 2017, 8:13 AM
Petko Bozhkov
Petko Bozhkov - avatar
+ 5
In fact, there's a fourth way of adding elements to list: the list concanetation ability trough the use of the simple '+' operator... mylist = [1,2,3,4] mylist = mylist + [5,6,7] ... after what 'mylist' is equal to [1,2,3,4,5,6,7] Obviously, you can use it with list litteral as with list variable names ^^
8th Jul 2017, 3:39 PM
visph
visph - avatar