0

To continue my quiz series, explain what happens with this code (how you would name this action and is there other way to get same result), why, and what is actually the value of a at end.

a = ['a', 'b','e']
a[2:2] = ['c', 'd']

Edited by pyTony

2
Contributors
3
Replies
24
Views
2 Years
Discussion Span
Last Post by pyTony
0

a is initialized as

a b e
0 1 2

An easy way to visualize a[2:2] is to consider a[2:3], which references ['e']. Thus, a[2:2] refences the empty list before 'e'. Setting a[2:2] = ['c', 'd'] inserts c&d after 'b', giving the final result of: ['a', 'b', 'c', 'd', 'e'].

This is just called inserting into a list. There are plently of other ways to do this. Python supplies a list.insert() method. You could also pop the end off the list until you reach your desired entry point, extend/append your own list/elements on, and push the back back on.

0

Sorry, I should have explaind that list.insert() only inserts one element at a time, so you'll need to read in your elements individually for it to work.

Edited by Hiroshe

0

Yes, the point is that it is not insert, but append inside. So instead the alternative is slicing and addition. This thread is BTW not a question but food for thought, you might next time wait little time until posting visibly answer, even everyone can see what the result actually is. But I think the real spectrum of slicing is not usually covered by the programming courses. Say for example my old stackoverflow post on most optimized prime sieve: http://stackoverflow.com/questions/3285443/improving-pure-python-prime-sieve-by-recurrence-formula

Edited by pyTony

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.