473,804 Members | 4,272 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Lists: why is this behavior different for index and slice assignments?

Hey all. I've decided I let my Python skills (minor though they were)
slip away so I started reading the new edition of Learning Python to
brush up. I just read about lists again and I'm wondering if someone
could explain what's going on under the hood that makes index and slice
assignments behave differently when assigning an empty list.

For example:
>>L = [1, 2, 3, 4, 5]
L[0:2] = []
L
[3, 4, 5]
>>L = [1, 2, 3, 4, 5]
L[0] = []
L
[[], 2, 3, 4, 5]

So the question is, when you assign an empty list to an index, why does
it insert an empty list, but when you assign an empty list to a slice,
it simply deletes the slice?

Thanks!
Jun 27 '08 #1
8 1541
John Salerno wrote:
So the question is, when you assign an empty list to an index, why does
it insert an empty list, but when you assign an empty list to a slice,
it simply deletes the slice?
I would say this is consistent behavior because a list slice is also a
list itself. Whereas a list element is just that. A reference to an
object that can be rebound. In the latter case you are rebinding a
single list item to an empty list.
Jun 27 '08 #2
John Salerno wrote:
Hey all. I've decided I let my Python skills (minor though they were)
slip away so I started reading the new edition of Learning Python to
brush up. I just read about lists again and I'm wondering if someone
could explain what's going on under the hood that makes index and slice
assignments behave differently when assigning an empty list.

For example:
>>L = [1, 2, 3, 4, 5]
>>L[0:2] = []
>>L
[3, 4, 5]
>>L = [1, 2, 3, 4, 5]
>>L[0] = []
>>L
[[], 2, 3, 4, 5]

So the question is, when you assign an empty list to an index, why does
it insert an empty list, but when you assign an empty list to a slice,
it simply deletes the slice?
Assignment to a list *element* rebinds the single element to the
assigned value. Assignment to a list *slice* has to be of a list, and it
replaces the elements in the slice by assigned elements.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Jun 27 '08 #3
Steve Holden <st***@holdenwe b.comwrote:
Assignment to a list *element* rebinds the single element to the
assigned value. Assignment to a list *slice* has to be of a list, and it
replaces the elements in the slice by assigned elements.
Assignment to a list *slice* just has use an iterable, it doesn't actually
have to be another list.
Jun 27 '08 #4
Steve Holden wrote:
Assignment to a list *element* rebinds the single element to the
assigned value.
Ok, I understand that.

Assignment to a list *slice* has to be of a list [or iterable, as per
Duncan], and it
replaces the elements in the slice by assigned elements.

I don't understand the second part of that sentence. I'm assuming "it"
refers to the list being assigned, "replaces the elements" is
self-evident, but what does "by assigned elements" refer to? It seems
when you assign a list to a list slice, nothing gets replaced, the slice
just gets deleted.
Jun 27 '08 #5
John Salerno wrote:
Steve Holden wrote:
>Assignment to a list *element* rebinds the single element to the
assigned value.

Ok, I understand that.

Assignment to a list *slice* has to be of a list [or iterable, as per
Duncan], and it
>replaces the elements in the slice by assigned elements.


I don't understand the second part of that sentence. I'm assuming "it"
refers to the list being assigned, "replaces the elements" is
self-evident, but what does "by assigned elements" refer to? It seems
when you assign a list to a list slice, nothing gets replaced, the slice
just gets deleted.
Deletion occurs *only* in the corner case where there are no "assigned
elements" i.e. only if the RHS list (sequence) is *empty*. Otherwise
there would be no point at all in the language having assignment to a
slice -- del L[0:2] would suffice.

Study these:
>>L = [1, 2, 3, 4, 5]
L[0:2] = []
L
[3, 4, 5]
>>L = [1, 2, 3, 4, 5]
L[0:2] = ['whatever']
L
['whatever', 3, 4, 5]
>>L = [1, 2, 3, 4, 5]
L[0:2] = tuple('foobar')
L
['f', 'o', 'o', 'b', 'a', 'r', 3, 4, 5]
>>>
Jun 27 '08 #6
John Salerno wrote:
>replaces the elements in the slice by assigned elements.


I don't understand the second part of that sentence. I'm assuming "it"
refers to the list being assigned, "replaces the elements" is
self-evident, but what does "by assigned elements" refer to? It seems
when you assign a list to a list slice, nothing gets replaced, the slice
just gets deleted.
>>x = range(5)
x[0:3] = ["a", "b"]
x
['a', 'b', 3, 4]

Here, '= ["a", "b"]' replaces x[0:3] with ["a", "b"]. When you do '=
[]', it replaces them with nothing.
--
Jun 27 '08 #7
John Machin wrote:
Deletion occurs *only* in the corner case where there are no "assigned
elements" i.e. only if the RHS list (sequence) is *empty*.
Oh, it was my understanding that deletion always occurs, even when the
section is being assigned a non-empty value, i.e. delete the slice and
insert new value.

Otherwise
there would be no point at all in the language having assignment to a
slice -- del L[0:2] would suffice.
Right, but I'm wondering why a statement like

L[0:2] = []

doesn't assign an empty list as the new element in L. For example:

L = [1, 2, 3, 4, 5]
L[0:2] = []

Why doesn't L now equal [[], 3, 4, 5] as it does with an index assignment?
>>L[0:2] = tuple('foobar')
>>L
['f', 'o', 'o', 'b', 'a', 'r', 3, 4, 5]
Hmm...why doesn't L equal [('f', 'o', 'o', 'b', 'a', 'r'), 3, 4, 5] ?
Shouldn't L be a 4 item list instead of 9?
Jun 27 '08 #8

"John Salerno" <jo******@gmail NOSPAM.comwrote in message
news:48******** *************** @cv.net...
| John Machin wrote:
|
| Deletion occurs *only* in the corner case where there are no "assigned
| elements" i.e. only if the RHS list (sequence) is *empty*.
|
| Oh, it was my understanding that deletion always occurs, even when the
| section is being assigned a non-empty value, i.e. delete the slice and
| insert new value.

Slice replacement means replace the slice with a new slice generated from
the iterable on the left. John meant that deletion only only happens when
the replacement is empty. Yes, deletion always occurs, but usually
addition also occurs, so the net result is replacement rather than just
deletion.

| Otherwise
| there would be no point at all in the language having assignment to a
| slice -- del L[0:2] would suffice.
|
| Right, but I'm wondering why a statement like
| L[0:2] = []
| doesn't assign an empty list as the new element in L. For example:

Because, as others already told you, slice replacement is slice
replacement, not item assignment. When you say to replace the slice with
nothing, the deleted slice is replaced with nothing.

L[0:2] = [[]]

says to replace the slice with a slice consisting of one item -- []
That will get you what you are expecting.

| L = [1, 2, 3, 4, 5]
| L[0:2] = []
|
| Why doesn't L now equal [[], 3, 4, 5] as it does with an index
assignment?

See above.

|
| >>L[0:2] = tuple('foobar')

L[0:2] = 'foobar' has same effect because s string is an iterable.

| >>L
| ['f', 'o', 'o', 'b', 'a', 'r', 3, 4, 5]
|
| Hmm...why doesn't L equal [('f', 'o', 'o', 'b', 'a', 'r'), 3, 4, 5] ?
| Shouldn't L be a 4 item list instead of 9?

Because you replaced 2 items with 6.

L[0:2] = ['foobar'] will replace 2 with 1, leaving 4

tjr

Jun 27 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
4338
by: Hilde Roth | last post by:
This may have been asked before but I can't find it. If I have a rectangular list of lists, say, l = ,,], is there a handy syntax for retrieving the ith item of every sublist? I know about for i in l] but I was hoping for something more like l. Hilde
18
2519
by: jblazi | last post by:
I should like to search certain characters in a string and when they are found, I want to replace other characters in other strings that are at the same position (for a very simply mastermind game) for my pupils. This very simple thing does not seem simple at all. If I use strings, I cannot replace their parts (though I can use string.find for the searching). I think it is a bad idea that strings are not mutable, but I suspect that...
2
1768
by: Uwe Mayer | last post by:
Hi, a class of mine should support the list interface and implements the __len__ and __getitem__ methods. Now when I ask for an unbounded slice: >>> len( myObj ) my __getitem__(self, y) method gets called with
9
2140
by: kosh | last post by:
I was wondering if there is or there could be some way to pass a generator an optional starting index so that if it supported that slicing could be made more efficient. Right now if you do use a generator and do a or any other kind of slice it reads all the values up to 100 also. I know a lot of generators have to do all previous parts before they can do the next part but it would be a nice optimization that can start at any index to...
10
2186
by: Philippe C. Martin | last post by:
Hi, I'm looking for an easy algorithm - maybe Python can help: I start with X lists which intial sort is based on list #1. I want to reverse sort list #1 and have all other lists sorted accordingly. Any idea is welcome.
6
2187
by: xkenneth | last post by:
Looking to do something similair. I'm working with alot of timestamps and if they're within a couple seconds I need them to be indexed and removed from a list. Is there any possible way to index with a custom cmp() function? I assume it would be something like... list.index(something,mycmp) Thanks!
19
1992
RMWChaos
by: RMWChaos | last post by:
Previously, I had used independent JSON lists in my code, where the lists were part of separate scripts. Because this method did not support reuse of a script without modification, I decided to consolidate all my JSON lists into one and modify my scripts so that they were more generic and reusable. So far so good. The problem is that my JSON lists used variables for many pieces of code that performed multiple iterations to create several...
3
1286
by: jmDesktop | last post by:
This program: s = 'abcde' i = -1 for i in range (-1, -len(s), -1): print s, i gives abcd -1
33
12226
by: Andreas Prilop | last post by:
To get bold numbers in ordered lists, one can write ol { font-weight: bold } ol span { font-weight: normal } <ol> <li><span>......</span></li> <li><span>......</span></li> </ol>
0
9710
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9589
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10340
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10329
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10085
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4304
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3830
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.