![]() |
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. |
I think it's as easy as
:
list.insert(i, x) |
What andro says.
:
list = range(5) # create a list of 5 elements, from 0 to 4 |
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']Any questions, feel free to ask. |
Thanks everyone! The python sub-forum seems a lot friendlier than the HTML forum :)
Sane that's a great tip! |
Quote:
-T. (no, I can't test it ;-P) |
hydroxide, you are right
:
# this inserts 'new' at index 3 |
Ah, that's interesting. Very abstract sort of logic, would have never though of that to work.
|
Actually I found it in one of the Python Reference Manuals:
Quote:
|
| All times are GMT -5. The time now is 6:41 PM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC