![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programmer
Join Date: Nov 2005
Location: Estonia
Posts: 97
Rep Power: 0
![]() |
Appending to a certain index in a list
I have a list with 5 elements. I want to change the 3rd element and to move the elements forward (3>4, 4>5, 5>6) at the same time. Is there a simple way to do this or do I have to do something mad?
I'm sorry if this is stupid, but I'm a beginner. |
|
|
|
|
|
#2 |
|
Professional Programmer
|
|
|
|
|
|
|
#3 |
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5
![]() |
What andro says.
list = range(5) # create a list of 5 elements, from 0 to 4 list.insert(2, 9) # change the 3rd element 9 and move the rest forward # (Indicies start from 0, so the index of 2 refers to the 3rd element) |
|
|
|
|
|
#4 |
|
Programming Guru
![]() ![]() |
Also, it may be a good idea to become familiar with list indexing. Yes, Andro's code works perfectly for what you need to do. However, there will be times when you need to use an alternative method (for other purposes, eg. replacing the third element), list indexing...
my_list = ['a', 'b', 'c', 'd', 'e'] new_list = my_list[:3] + ['new'] + my_list[3:] # essentially: ['a', 'b', 'c'] + ['new'] + ['d', 'e'] print new_list Any questions, feel free to ask. |
|
|
|
|
|
#5 |
|
Programmer
Join Date: Nov 2005
Location: Estonia
Posts: 97
Rep Power: 0
![]() |
Thanks everyone! The python sub-forum seems a lot friendlier than the HTML forum
![]() Sane that's a great tip! |
|
|
|
|
|
#6 | |
|
Programmer
Join Date: Apr 2005
Posts: 73
Rep Power: 4
![]() |
Quote:
-T. (no, I can't test it ;-P) |
|
|
|
|
|
|
#7 |
|
Professional Programmer
Join Date: Feb 2005
Posts: 434
Rep Power: 4
![]() |
hydroxide, you are right
# this inserts 'new' at index 3 my_list = ['a', 'b', 'c', 'd', 'e'] my_list[3:3] = ['new'] print my_list # ['a', 'b', 'c', 'new', 'd', 'e']
__________________
I looked it up on the Intergnats! |
|
|
|
|
|
#8 |
|
Programming Guru
![]() ![]() |
Ah, that's interesting. Very abstract sort of logic, would have never though of that to work.
|
|
|
|
|
|
#9 | |
|
Professional Programmer
Join Date: Feb 2005
Posts: 434
Rep Power: 4
![]() |
Actually I found it in one of the Python Reference Manuals:
Quote:
__________________
I looked it up on the Intergnats! |
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|