Why is extended slice assignment less flexible than regular slice assignment?2019 Community Moderator ElectionList assignment using slice-Anomalous behaviourAssigning a value to an element of a slice in PythonWhy don't Java's +=, -=, *=, /= compound assignment operators require casting?Why is reading lines from stdin much slower in C++ than Python?What is the difference between slice assignment that slices the whole list and direct assignment?Python 3: do strings have __next__() method?Compact way to assign values by slicing list in PythonWhy is 'x' in ('x',) faster than 'x' == 'x'?Why is [] faster than list()?Why does assigning past the end of a list via a slice not raise an IndexError?list assignment in python using slicing

How do I hide Chekhov's Gun?

World War I as a war of liberals against authoritarians?

Have the tides ever turned twice on any open problem?

Is there a hypothetical scenario that would make Earth uninhabitable for humans, but not for (the majority of) other animals?

Print a physical multiplication table

About the actual radiative impact of greenhouse gas emission over time

How can we have a quark condensate without a quark potential?

Employee lack of ownership

How difficult is it to simply disable/disengage the MCAS on Boeing 737 Max 8 & 9 Aircraft?

How could a scammer know the apps on my phone / iTunes account?

Is a party consisting of only a bard, a cleric, and a warlock functional long-term?

Non-trivial topology where only open sets are closed

Brexit - No Deal Rejection

Adventure Game (text based) in C++

Can I use USB data pins as a power source?

Simplify an interface for flexibly applying rules to periods of time

Is there a symmetric-key algorithm which we can use for creating a signature?

Why did it take so long to abandon sail after steamships were demonstrated?

What's the meaning of a knight fighting a snail in medieval book illustrations?

Why does a Star of David appear at a rally with Francisco Franco?

If I can solve Sudoku, can I solve the Travelling Salesman Problem (TSP)? If so, how?

ERC721: How to get the owned tokens of an address

How should I state my peer review experience in the CV?

What options are left, if Britain cannot decide?



Why is extended slice assignment less flexible than regular slice assignment?



2019 Community Moderator ElectionList assignment using slice-Anomalous behaviourAssigning a value to an element of a slice in PythonWhy don't Java's +=, -=, *=, /= compound assignment operators require casting?Why is reading lines from stdin much slower in C++ than Python?What is the difference between slice assignment that slices the whole list and direct assignment?Python 3: do strings have __next__() method?Compact way to assign values by slicing list in PythonWhy is 'x' in ('x',) faster than 'x' == 'x'?Why is [] faster than list()?Why does assigning past the end of a list via a slice not raise an IndexError?list assignment in python using slicing










2















According to the Python documentation on extended slices:




If you have a mutable sequence such as a list or an array you can
assign to or delete an extended slice, but there are some differences
between assignment to extended and regular slices. Assignment to a
regular slice can be used to change the length of the sequence:



>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]


Extended slices aren't this flexible. When assigning to an extended
slice, the list on the right hand side of the statement must contain
the same number of items as the slice it is replacing:



>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = [0, -1]
>>> a
[0, 1, -1, 3]
>>> a[::2] = [0,1,2]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2



I do not understand why the "ordinary" slice method works but the "extended" slice method doesn't work. What differentiates an "ordinary" slice from an "extended" slice, and why does the "extended" slice method fail?










share|improve this question



















  • 2





    What differentiates it is the third parameter, the step, as described in the opening paragraph. It fails because the list on the right hand side of the statement does not contain the same number of items (3) as the slice it is replacing (2), which is what the text you've copied says is required. That's why they use it as an illustration for that description. It's unclear what you mean by "why".

    – jonrsharpe
    Dec 25 '17 at 11:55
















2















According to the Python documentation on extended slices:




If you have a mutable sequence such as a list or an array you can
assign to or delete an extended slice, but there are some differences
between assignment to extended and regular slices. Assignment to a
regular slice can be used to change the length of the sequence:



>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]


Extended slices aren't this flexible. When assigning to an extended
slice, the list on the right hand side of the statement must contain
the same number of items as the slice it is replacing:



>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = [0, -1]
>>> a
[0, 1, -1, 3]
>>> a[::2] = [0,1,2]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2



I do not understand why the "ordinary" slice method works but the "extended" slice method doesn't work. What differentiates an "ordinary" slice from an "extended" slice, and why does the "extended" slice method fail?










share|improve this question



















  • 2





    What differentiates it is the third parameter, the step, as described in the opening paragraph. It fails because the list on the right hand side of the statement does not contain the same number of items (3) as the slice it is replacing (2), which is what the text you've copied says is required. That's why they use it as an illustration for that description. It's unclear what you mean by "why".

    – jonrsharpe
    Dec 25 '17 at 11:55














2












2








2


1






According to the Python documentation on extended slices:




If you have a mutable sequence such as a list or an array you can
assign to or delete an extended slice, but there are some differences
between assignment to extended and regular slices. Assignment to a
regular slice can be used to change the length of the sequence:



>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]


Extended slices aren't this flexible. When assigning to an extended
slice, the list on the right hand side of the statement must contain
the same number of items as the slice it is replacing:



>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = [0, -1]
>>> a
[0, 1, -1, 3]
>>> a[::2] = [0,1,2]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2



I do not understand why the "ordinary" slice method works but the "extended" slice method doesn't work. What differentiates an "ordinary" slice from an "extended" slice, and why does the "extended" slice method fail?










share|improve this question
















According to the Python documentation on extended slices:




If you have a mutable sequence such as a list or an array you can
assign to or delete an extended slice, but there are some differences
between assignment to extended and regular slices. Assignment to a
regular slice can be used to change the length of the sequence:



>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]


Extended slices aren't this flexible. When assigning to an extended
slice, the list on the right hand side of the statement must contain
the same number of items as the slice it is replacing:



>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = [0, -1]
>>> a
[0, 1, -1, 3]
>>> a[::2] = [0,1,2]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2



I do not understand why the "ordinary" slice method works but the "extended" slice method doesn't work. What differentiates an "ordinary" slice from an "extended" slice, and why does the "extended" slice method fail?







python python-3.x list variable-assignment slice






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 25 '17 at 19:28









Zero Piraeus

30.9k18101127




30.9k18101127










asked Dec 25 '17 at 11:35









MPathMPath

7312616




7312616







  • 2





    What differentiates it is the third parameter, the step, as described in the opening paragraph. It fails because the list on the right hand side of the statement does not contain the same number of items (3) as the slice it is replacing (2), which is what the text you've copied says is required. That's why they use it as an illustration for that description. It's unclear what you mean by "why".

    – jonrsharpe
    Dec 25 '17 at 11:55













  • 2





    What differentiates it is the third parameter, the step, as described in the opening paragraph. It fails because the list on the right hand side of the statement does not contain the same number of items (3) as the slice it is replacing (2), which is what the text you've copied says is required. That's why they use it as an illustration for that description. It's unclear what you mean by "why".

    – jonrsharpe
    Dec 25 '17 at 11:55








2




2





What differentiates it is the third parameter, the step, as described in the opening paragraph. It fails because the list on the right hand side of the statement does not contain the same number of items (3) as the slice it is replacing (2), which is what the text you've copied says is required. That's why they use it as an illustration for that description. It's unclear what you mean by "why".

– jonrsharpe
Dec 25 '17 at 11:55






What differentiates it is the third parameter, the step, as described in the opening paragraph. It fails because the list on the right hand side of the statement does not contain the same number of items (3) as the slice it is replacing (2), which is what the text you've copied says is required. That's why they use it as an illustration for that description. It's unclear what you mean by "why".

– jonrsharpe
Dec 25 '17 at 11:55













1 Answer
1






active

oldest

votes


















4














It's a little easier to see the problem if you try to imagine how



a[::3] = [0, 1, 2]


would work with a 4-item list:



+---+---+---+---+ + +---+
| a | b | c | d | | ? |
+---+---+---+---+ + +---+
^ ^ ^
+---+ +---+ +---+
| 0 | | 1 | | 2 |
+---+ +---+ +---+


We're trying to replace every third value, but our list isn't long enough, so if we went ahead anyway we'd end up with some kind of weird frankenstein list where some of the items don't actually exist. If someone then tried to access a[5] and got an IndexError (even though a[6] works normally), they'd get really confused.



Although you could technically get away with the a[::2] case by extending a by one, for the sake of consistency, Python bans all extended slicing assignments are unless there's already a place for the value to go.



A regular slice always has a stride of one, so there's no chance of any gaps occurring, and so the assignment can safely be allowed.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47968232%2fwhy-is-extended-slice-assignment-less-flexible-than-regular-slice-assignment%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    4














    It's a little easier to see the problem if you try to imagine how



    a[::3] = [0, 1, 2]


    would work with a 4-item list:



    +---+---+---+---+ + +---+
    | a | b | c | d | | ? |
    +---+---+---+---+ + +---+
    ^ ^ ^
    +---+ +---+ +---+
    | 0 | | 1 | | 2 |
    +---+ +---+ +---+


    We're trying to replace every third value, but our list isn't long enough, so if we went ahead anyway we'd end up with some kind of weird frankenstein list where some of the items don't actually exist. If someone then tried to access a[5] and got an IndexError (even though a[6] works normally), they'd get really confused.



    Although you could technically get away with the a[::2] case by extending a by one, for the sake of consistency, Python bans all extended slicing assignments are unless there's already a place for the value to go.



    A regular slice always has a stride of one, so there's no chance of any gaps occurring, and so the assignment can safely be allowed.






    share|improve this answer



























      4














      It's a little easier to see the problem if you try to imagine how



      a[::3] = [0, 1, 2]


      would work with a 4-item list:



      +---+---+---+---+ + +---+
      | a | b | c | d | | ? |
      +---+---+---+---+ + +---+
      ^ ^ ^
      +---+ +---+ +---+
      | 0 | | 1 | | 2 |
      +---+ +---+ +---+


      We're trying to replace every third value, but our list isn't long enough, so if we went ahead anyway we'd end up with some kind of weird frankenstein list where some of the items don't actually exist. If someone then tried to access a[5] and got an IndexError (even though a[6] works normally), they'd get really confused.



      Although you could technically get away with the a[::2] case by extending a by one, for the sake of consistency, Python bans all extended slicing assignments are unless there's already a place for the value to go.



      A regular slice always has a stride of one, so there's no chance of any gaps occurring, and so the assignment can safely be allowed.






      share|improve this answer

























        4












        4








        4







        It's a little easier to see the problem if you try to imagine how



        a[::3] = [0, 1, 2]


        would work with a 4-item list:



        +---+---+---+---+ + +---+
        | a | b | c | d | | ? |
        +---+---+---+---+ + +---+
        ^ ^ ^
        +---+ +---+ +---+
        | 0 | | 1 | | 2 |
        +---+ +---+ +---+


        We're trying to replace every third value, but our list isn't long enough, so if we went ahead anyway we'd end up with some kind of weird frankenstein list where some of the items don't actually exist. If someone then tried to access a[5] and got an IndexError (even though a[6] works normally), they'd get really confused.



        Although you could technically get away with the a[::2] case by extending a by one, for the sake of consistency, Python bans all extended slicing assignments are unless there's already a place for the value to go.



        A regular slice always has a stride of one, so there's no chance of any gaps occurring, and so the assignment can safely be allowed.






        share|improve this answer













        It's a little easier to see the problem if you try to imagine how



        a[::3] = [0, 1, 2]


        would work with a 4-item list:



        +---+---+---+---+ + +---+
        | a | b | c | d | | ? |
        +---+---+---+---+ + +---+
        ^ ^ ^
        +---+ +---+ +---+
        | 0 | | 1 | | 2 |
        +---+ +---+ +---+


        We're trying to replace every third value, but our list isn't long enough, so if we went ahead anyway we'd end up with some kind of weird frankenstein list where some of the items don't actually exist. If someone then tried to access a[5] and got an IndexError (even though a[6] works normally), they'd get really confused.



        Although you could technically get away with the a[::2] case by extending a by one, for the sake of consistency, Python bans all extended slicing assignments are unless there's already a place for the value to go.



        A regular slice always has a stride of one, so there's no chance of any gaps occurring, and so the assignment can safely be allowed.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 25 '17 at 19:22









        Zero PiraeusZero Piraeus

        30.9k18101127




        30.9k18101127





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47968232%2fwhy-is-extended-slice-assignment-less-flexible-than-regular-slice-assignment%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived