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']

Recommended Answers

All 3 Replies

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.

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.