LISTS

0 Pawan Terdal · July 7, 2015
How do we add a number in between two numbers in a list ?

Post a Reply

Replies

Oldest  Newest  Rating
0 Ebenezer Popoola · July 7, 2015
Hi, i guess you want this.
>>> numbers = [1,3,4,5]  # note, 2 is missing in this list
>>> numbers.insert(1,2) #  we can insert 2 in position 1
>>> numbers
[1, 2, 3, 4, 5] 
0 Otto Von Chesterfield · July 7, 2015
Just looked at the pydocs and the command you need is list.insert.

Here's some code for it:
knights = ['eggs', 'ham']
knights.insert(1, 'spam') # Insert 'spam' right before knights[1]
print(knights)

# Output:
# ['eggs', 'spam', 'ham']

If you ever need list help, you can go to the IDLE command line and type:
help(list) #The list var is actually an object!


You can do this for all objects - as well as special keywords (such as for, in, while etc.) if you surround it with quotes.

Hope this helps!
  • 1

Python

107,237 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator