Periodically replacing values in a list

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
20
down vote

favorite
3












Suppose I have the following list in Python:



my_list = [10] * 95


Given n, I want to replace any other m elements with zero in my list, while keeping the next n elements.



For example, if n = 3 and m = 2, I want my list to look like:



[10, 10, 10, 0, 0, 10, 10, 10 ,0, 0, ..., 10, 10, 10 , 0, 0]


If it can't be filled perfectly, as is the case with n = 4 and m = 2, then it's OK if my list looks like this:



[10, 10, 10, 10, 0, 0, ..., 10, 10, 10, 10, 0]


How should I try to solve this problem?










share|improve this question























  • Will the input list always be filled with one and the same value (like 10 in your example)? In other words, do you want to create a new list like [10, 10, 10, 0, 0, ...] or do you want to overwrite every nth value in an existing list?
    – Aran-Fey
    Sep 25 at 8:13







  • 6




    How is this question not worth closing? The OP basically asks for an answer without any visible effort to have tried something
    – Denny
    Sep 25 at 11:15







  • 1




    @Denny, in the beginning, I was also very confused about this system on this site. 3 criteria for a good question: 1) (visible) effort. 2) Useful and 3) Clear. And more than not, the two last criteria score higher on the priority list for most users. If you browse this and other stack exchange sites, you'll find countless examples of questions that don't show the visible effort, but are just useful (and maybe more importantly) clear for other users.
    – Riley
    Sep 25 at 11:22







  • 3




    Personally, I think the question is very specific, and it's quite unlikely that somebody will come across it and found this question through a Google search (without knowing about the question in advance, of course); besides, it's pretty basic.
    – user202729
    Sep 25 at 13:08






  • 3




    It's easy -> it gets many answers -> the "hotness formula" think (no comment on the formula) it's hot -> it's displayed on the HNQ list -> it attracts more viewers, mostly not come from Stack Overflow. Besides it's not possible to understand the question just by reading the title (because it's specific!) so the viewer is forced to click on the link, that generates view.
    – user202729
    Sep 25 at 15:17














up vote
20
down vote

favorite
3












Suppose I have the following list in Python:



my_list = [10] * 95


Given n, I want to replace any other m elements with zero in my list, while keeping the next n elements.



For example, if n = 3 and m = 2, I want my list to look like:



[10, 10, 10, 0, 0, 10, 10, 10 ,0, 0, ..., 10, 10, 10 , 0, 0]


If it can't be filled perfectly, as is the case with n = 4 and m = 2, then it's OK if my list looks like this:



[10, 10, 10, 10, 0, 0, ..., 10, 10, 10, 10, 0]


How should I try to solve this problem?










share|improve this question























  • Will the input list always be filled with one and the same value (like 10 in your example)? In other words, do you want to create a new list like [10, 10, 10, 0, 0, ...] or do you want to overwrite every nth value in an existing list?
    – Aran-Fey
    Sep 25 at 8:13







  • 6




    How is this question not worth closing? The OP basically asks for an answer without any visible effort to have tried something
    – Denny
    Sep 25 at 11:15







  • 1




    @Denny, in the beginning, I was also very confused about this system on this site. 3 criteria for a good question: 1) (visible) effort. 2) Useful and 3) Clear. And more than not, the two last criteria score higher on the priority list for most users. If you browse this and other stack exchange sites, you'll find countless examples of questions that don't show the visible effort, but are just useful (and maybe more importantly) clear for other users.
    – Riley
    Sep 25 at 11:22







  • 3




    Personally, I think the question is very specific, and it's quite unlikely that somebody will come across it and found this question through a Google search (without knowing about the question in advance, of course); besides, it's pretty basic.
    – user202729
    Sep 25 at 13:08






  • 3




    It's easy -> it gets many answers -> the "hotness formula" think (no comment on the formula) it's hot -> it's displayed on the HNQ list -> it attracts more viewers, mostly not come from Stack Overflow. Besides it's not possible to understand the question just by reading the title (because it's specific!) so the viewer is forced to click on the link, that generates view.
    – user202729
    Sep 25 at 15:17












up vote
20
down vote

favorite
3









up vote
20
down vote

favorite
3






3





Suppose I have the following list in Python:



my_list = [10] * 95


Given n, I want to replace any other m elements with zero in my list, while keeping the next n elements.



For example, if n = 3 and m = 2, I want my list to look like:



[10, 10, 10, 0, 0, 10, 10, 10 ,0, 0, ..., 10, 10, 10 , 0, 0]


If it can't be filled perfectly, as is the case with n = 4 and m = 2, then it's OK if my list looks like this:



[10, 10, 10, 10, 0, 0, ..., 10, 10, 10, 10, 0]


How should I try to solve this problem?










share|improve this question















Suppose I have the following list in Python:



my_list = [10] * 95


Given n, I want to replace any other m elements with zero in my list, while keeping the next n elements.



For example, if n = 3 and m = 2, I want my list to look like:



[10, 10, 10, 0, 0, 10, 10, 10 ,0, 0, ..., 10, 10, 10 , 0, 0]


If it can't be filled perfectly, as is the case with n = 4 and m = 2, then it's OK if my list looks like this:



[10, 10, 10, 10, 0, 0, ..., 10, 10, 10, 10, 0]


How should I try to solve this problem?







python list replace






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 25 at 8:08









Aran-Fey

20.4k53165




20.4k53165










asked Sep 25 at 8:00









Riley

280113




280113











  • Will the input list always be filled with one and the same value (like 10 in your example)? In other words, do you want to create a new list like [10, 10, 10, 0, 0, ...] or do you want to overwrite every nth value in an existing list?
    – Aran-Fey
    Sep 25 at 8:13







  • 6




    How is this question not worth closing? The OP basically asks for an answer without any visible effort to have tried something
    – Denny
    Sep 25 at 11:15







  • 1




    @Denny, in the beginning, I was also very confused about this system on this site. 3 criteria for a good question: 1) (visible) effort. 2) Useful and 3) Clear. And more than not, the two last criteria score higher on the priority list for most users. If you browse this and other stack exchange sites, you'll find countless examples of questions that don't show the visible effort, but are just useful (and maybe more importantly) clear for other users.
    – Riley
    Sep 25 at 11:22







  • 3




    Personally, I think the question is very specific, and it's quite unlikely that somebody will come across it and found this question through a Google search (without knowing about the question in advance, of course); besides, it's pretty basic.
    – user202729
    Sep 25 at 13:08






  • 3




    It's easy -> it gets many answers -> the "hotness formula" think (no comment on the formula) it's hot -> it's displayed on the HNQ list -> it attracts more viewers, mostly not come from Stack Overflow. Besides it's not possible to understand the question just by reading the title (because it's specific!) so the viewer is forced to click on the link, that generates view.
    – user202729
    Sep 25 at 15:17
















  • Will the input list always be filled with one and the same value (like 10 in your example)? In other words, do you want to create a new list like [10, 10, 10, 0, 0, ...] or do you want to overwrite every nth value in an existing list?
    – Aran-Fey
    Sep 25 at 8:13







  • 6




    How is this question not worth closing? The OP basically asks for an answer without any visible effort to have tried something
    – Denny
    Sep 25 at 11:15







  • 1




    @Denny, in the beginning, I was also very confused about this system on this site. 3 criteria for a good question: 1) (visible) effort. 2) Useful and 3) Clear. And more than not, the two last criteria score higher on the priority list for most users. If you browse this and other stack exchange sites, you'll find countless examples of questions that don't show the visible effort, but are just useful (and maybe more importantly) clear for other users.
    – Riley
    Sep 25 at 11:22







  • 3




    Personally, I think the question is very specific, and it's quite unlikely that somebody will come across it and found this question through a Google search (without knowing about the question in advance, of course); besides, it's pretty basic.
    – user202729
    Sep 25 at 13:08






  • 3




    It's easy -> it gets many answers -> the "hotness formula" think (no comment on the formula) it's hot -> it's displayed on the HNQ list -> it attracts more viewers, mostly not come from Stack Overflow. Besides it's not possible to understand the question just by reading the title (because it's specific!) so the viewer is forced to click on the link, that generates view.
    – user202729
    Sep 25 at 15:17















Will the input list always be filled with one and the same value (like 10 in your example)? In other words, do you want to create a new list like [10, 10, 10, 0, 0, ...] or do you want to overwrite every nth value in an existing list?
– Aran-Fey
Sep 25 at 8:13





Will the input list always be filled with one and the same value (like 10 in your example)? In other words, do you want to create a new list like [10, 10, 10, 0, 0, ...] or do you want to overwrite every nth value in an existing list?
– Aran-Fey
Sep 25 at 8:13





6




6




How is this question not worth closing? The OP basically asks for an answer without any visible effort to have tried something
– Denny
Sep 25 at 11:15





How is this question not worth closing? The OP basically asks for an answer without any visible effort to have tried something
– Denny
Sep 25 at 11:15





1




1




@Denny, in the beginning, I was also very confused about this system on this site. 3 criteria for a good question: 1) (visible) effort. 2) Useful and 3) Clear. And more than not, the two last criteria score higher on the priority list for most users. If you browse this and other stack exchange sites, you'll find countless examples of questions that don't show the visible effort, but are just useful (and maybe more importantly) clear for other users.
– Riley
Sep 25 at 11:22





@Denny, in the beginning, I was also very confused about this system on this site. 3 criteria for a good question: 1) (visible) effort. 2) Useful and 3) Clear. And more than not, the two last criteria score higher on the priority list for most users. If you browse this and other stack exchange sites, you'll find countless examples of questions that don't show the visible effort, but are just useful (and maybe more importantly) clear for other users.
– Riley
Sep 25 at 11:22





3




3




Personally, I think the question is very specific, and it's quite unlikely that somebody will come across it and found this question through a Google search (without knowing about the question in advance, of course); besides, it's pretty basic.
– user202729
Sep 25 at 13:08




Personally, I think the question is very specific, and it's quite unlikely that somebody will come across it and found this question through a Google search (without knowing about the question in advance, of course); besides, it's pretty basic.
– user202729
Sep 25 at 13:08




3




3




It's easy -> it gets many answers -> the "hotness formula" think (no comment on the formula) it's hot -> it's displayed on the HNQ list -> it attracts more viewers, mostly not come from Stack Overflow. Besides it's not possible to understand the question just by reading the title (because it's specific!) so the viewer is forced to click on the link, that generates view.
– user202729
Sep 25 at 15:17




It's easy -> it gets many answers -> the "hotness formula" think (no comment on the formula) it's hot -> it's displayed on the HNQ list -> it attracts more viewers, mostly not come from Stack Overflow. Besides it's not possible to understand the question just by reading the title (because it's specific!) so the viewer is forced to click on the link, that generates view.
– user202729
Sep 25 at 15:17












8 Answers
8






active

oldest

votes

















up vote
25
down vote



accepted










my_list = [10] * 95
n = 3
m = 2
for i in range(m):
my_list[n+i::m+n] = [0] * len(my_list[n+i::m+n])


This just needs m assignments to do the job (and m probably is small).



If you really just have two possible values (e. g. 10 and 0), you can do it even simpler:



my_list = [ 10 if i % (n+m) < n else 0 for i in range(95) ]


But that iterates in Python over the whole range of 95, so probably is not very fast.



A bit more complex but probably more efficient (especially for huge lists and large values for n and m) would be this:



my_list = (([ 10 ] * n + [ 0 ] * m) * (95 // (n + m) + 1))[:95]


But it builds internally lots of lists, so its up to tests to find out whether this is efficient in your case. (Also memory consumption should be taken into account for large lists.)



If you can use numpy (a bit off the question, but since it's widespread):



my_list = (np.arange(95) % (n+m) < n) * 10





share|improve this answer






















  • Could you post your 3 different solutions as 3 separate answers, please? I want to upvote the 2nd one, but the others... not so much.
    – Aran-Fey
    Sep 25 at 8:43






  • 3




    @Aran-Fey That would be overkill, I guess. Feel free to not upvote in this case, even if an upvote just states that the answer provided any help (not was perfect). And consider that the second one is probably the slowest of the four (only relevant for large numbers of course).
    – Alfe
    Sep 25 at 10:47

















up vote
27
down vote













You could use itertools.cycle to create an endless sequence of [10, 10, 10, 0, 0] and then take the first 95 elements of that sequence with itertools.islice:



n = 3
m = 2

pattern = [10] * n + [0] * m
my_list = list(itertools.islice(itertools.cycle(pattern), 95))





share|improve this answer




















  • Why use itertools when you can use list expression?
    – Moonsik Park
    Sep 25 at 8:28






  • 5




    @MoonsikPark Not sure what you mean. If you're referring to your own solution: Because I think mine is more readable than yours.
    – Aran-Fey
    Sep 25 at 8:29

















up vote
7
down vote













Yet another possibility, this time with enumerate:



[x * (i % (n + m) < n) for i, x in enumerate(my_list)]


It uses the fact that False and True are equal to 0 and 1 in Python (see here).



As a bonus, it works fine even if the list isn't constant:



>>> n = 4
>>> m = 2
>>> my_list = range(20)
>>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
[0, 1, 2, 3, 0, 0, 6, 7, 8, 9, 0, 0, 12, 13, 14, 15, 0, 0, 18, 19]


If the list contains strings, it replaces them with an empty string instead of 0:



>>> my_list = 'abcdefghijk'
>>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
['a', 'b', 'c', 'd', '', '', 'g', 'h', 'i', 'j', '']





share|improve this answer



























    up vote
    6
    down vote













    This worked for me:



    list = [10] * 95

    n = 4
    m = 2

    amask = np.tile(np.concatenate((np.ones(n),np.zeros(m))),int((len(list)+1)/(n+m)))[:len(list)]

    list = np.asarray(list)*amask


    which outputs:



    array([10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
    10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10.,
    10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10.,
    10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10.,
    0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0.,
    0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0.,
    10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
    10., 10., 10., 0.])


    The code takes n and m and constructs a mask of ones and zeros with a length matching your initial list using the np.tile function. Afterwards you just multiply the mask onto the list and get the zeros where you want them to be. It should also be flexibel to different lengths of the list and an (almost) arbitrary choice of n and m.



    You can cast the array back to a list if you want.






    share|improve this answer


















    • 1




      numpy? For real?
      – Alfe
      Sep 25 at 8:19






    • 1




      @Alfe: What's the problem with numpy? It's widespread and it's specifically designed for lists/arrays.
      – Eric Duminil
      Sep 25 at 9:51










    • @EricDuminil Just overkill for the job, that's all. It's like asking for a print() and getting a f=open('/dev/stdout', 'w'); f.write("foo"); f.flush(); f.close(). Works, yeah. But adds unnecessary complexity.
      – Alfe
      Sep 25 at 10:41







    • 1




      Btw, in numpy, I would have done it as (np.arange(95) % 5 < 3) * 10.
      – Alfe
      Sep 25 at 10:44






    • 3




      @Alfe Indeed, your accepted version is much more elegant -> +1. But nevertheless my suggestion also gets the job done and sometimes that's all you need. Thanks for pointing it out though.
      – Shintlor
      Sep 25 at 12:19

















    up vote
    4
    down vote













    How about this?



    my_list = [10] * 95
    n = 3
    m = 2

    for i in range(n, len(my_list)-1, n+m):
    my_list[i:i+m] = [0]*m

    print(my_list)



    Edit



    I found out that the above code changes the length of resulting list in some cases.



    >>> a = [1,2,3]
    >>> a[2:4] = [0] * 2
    >>> a
    [1, 2, 0, 0]


    Thus, the length should be restored somehow.



    my_list = [10] * 95
    cp_list = list(my_list)
    n = 3
    m = 5

    for i in range(n, len(my_list)-1, n+m):
    cp_list[i:i+m] = [0]*m

    cp_list = cp_list[:len(my_list)]
    print(cp_list)





    share|improve this answer


















    • 1




      Nice approach. But only if len(my_list) is smaller than m, this is more efficient than my solution.
      – Alfe
      Sep 25 at 8:24






    • 1




      There is a downvote on this answer but no critic comment. Downvoter, please comment on what you didn't like.
      – Alfe
      Sep 25 at 8:29






    • 2




      For deleting the last elements of a list, best use del cp_list[n:].
      – Alfe
      Sep 25 at 14:58

















    up vote
    3
    down vote













    numpy can do this pretty concisely, too!



    a = np.array(my_list).reshape(-1, n + m)
    a[:, n:] = 0
    result = a.ravel().tolist()





    share|improve this answer
















    • 2




      It doesn't seem to work with n = 4 and m = 2. It raises ValueError: cannot reshape array of size 95 into shape (6).
      – Eric Duminil
      Sep 25 at 9:57










    • @EricDuminil shouldn't an error be raised if the length of the original list is not a multiple of the length of the subsequences to be repeated?
      – timgeb
      Sep 25 at 10:02











    • Please take a look at the second half of the question. This use case is specifically mentioned by OP.
      – Eric Duminil
      Sep 25 at 10:03






    • 3




      @EricDuminil you are right. This answer does not work in the latter case.
      – timgeb
      Sep 25 at 10:05

















    up vote
    3
    down vote













    [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]


    Maybe?



    Result



    >>> num, input_num, m, n=95, 10, 2, 3
    >>> [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
    [10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0 , 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0]





    share|improve this answer


















    • 3




      I guess the list full of 10 is just for an example...
      – Julien
      Sep 25 at 8:07










    • @Julien No, OP said ' it can be any number, but it will always be the same one' so it will be full of any same number.
      – Moonsik Park
      Sep 25 at 8:20







    • 1




      1) Your output is incorrect (it's [10, 10, 0, 0, 0] instead of [10, 10, 10, 0, 0]) 2) Concatenating lists with sum is an antipattern with a massive run time complexity.
      – Aran-Fey
      Sep 25 at 8:34










    • @Aran-Fey Nope, it's correct.
      – Moonsik Park
      Sep 25 at 8:39










    • Oops. Indeed it is. Edited.
      – Moonsik Park
      Sep 25 at 8:44

















    up vote
    0
    down vote













    Also in the itertools family, you can repeat a desired pattern:



    Given



    import itertools as it


    m, n = 2, 3
    p = n + 1


    Code



    pattern = it.repeat([10] * n + [0] * m)
    res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
    print(res)
    # [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0, 0]




    pattern = it.repeat([10] * p + [0] * m)
    res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
    print(res)
    # [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0]


    Test



    assert len(res) == 95


    However, @Aran-Fey's itertools.cycle solution is cleaner as it does not require chaining.






    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',
      convertImagesToLinks: true,
      noModals: false,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      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%2f52493328%2fperiodically-replacing-values-in-a-list%23new-answer', 'question_page');

      );

      Post as a guest






























      8 Answers
      8






      active

      oldest

      votes








      8 Answers
      8






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      25
      down vote



      accepted










      my_list = [10] * 95
      n = 3
      m = 2
      for i in range(m):
      my_list[n+i::m+n] = [0] * len(my_list[n+i::m+n])


      This just needs m assignments to do the job (and m probably is small).



      If you really just have two possible values (e. g. 10 and 0), you can do it even simpler:



      my_list = [ 10 if i % (n+m) < n else 0 for i in range(95) ]


      But that iterates in Python over the whole range of 95, so probably is not very fast.



      A bit more complex but probably more efficient (especially for huge lists and large values for n and m) would be this:



      my_list = (([ 10 ] * n + [ 0 ] * m) * (95 // (n + m) + 1))[:95]


      But it builds internally lots of lists, so its up to tests to find out whether this is efficient in your case. (Also memory consumption should be taken into account for large lists.)



      If you can use numpy (a bit off the question, but since it's widespread):



      my_list = (np.arange(95) % (n+m) < n) * 10





      share|improve this answer






















      • Could you post your 3 different solutions as 3 separate answers, please? I want to upvote the 2nd one, but the others... not so much.
        – Aran-Fey
        Sep 25 at 8:43






      • 3




        @Aran-Fey That would be overkill, I guess. Feel free to not upvote in this case, even if an upvote just states that the answer provided any help (not was perfect). And consider that the second one is probably the slowest of the four (only relevant for large numbers of course).
        – Alfe
        Sep 25 at 10:47














      up vote
      25
      down vote



      accepted










      my_list = [10] * 95
      n = 3
      m = 2
      for i in range(m):
      my_list[n+i::m+n] = [0] * len(my_list[n+i::m+n])


      This just needs m assignments to do the job (and m probably is small).



      If you really just have two possible values (e. g. 10 and 0), you can do it even simpler:



      my_list = [ 10 if i % (n+m) < n else 0 for i in range(95) ]


      But that iterates in Python over the whole range of 95, so probably is not very fast.



      A bit more complex but probably more efficient (especially for huge lists and large values for n and m) would be this:



      my_list = (([ 10 ] * n + [ 0 ] * m) * (95 // (n + m) + 1))[:95]


      But it builds internally lots of lists, so its up to tests to find out whether this is efficient in your case. (Also memory consumption should be taken into account for large lists.)



      If you can use numpy (a bit off the question, but since it's widespread):



      my_list = (np.arange(95) % (n+m) < n) * 10





      share|improve this answer






















      • Could you post your 3 different solutions as 3 separate answers, please? I want to upvote the 2nd one, but the others... not so much.
        – Aran-Fey
        Sep 25 at 8:43






      • 3




        @Aran-Fey That would be overkill, I guess. Feel free to not upvote in this case, even if an upvote just states that the answer provided any help (not was perfect). And consider that the second one is probably the slowest of the four (only relevant for large numbers of course).
        – Alfe
        Sep 25 at 10:47












      up vote
      25
      down vote



      accepted







      up vote
      25
      down vote



      accepted






      my_list = [10] * 95
      n = 3
      m = 2
      for i in range(m):
      my_list[n+i::m+n] = [0] * len(my_list[n+i::m+n])


      This just needs m assignments to do the job (and m probably is small).



      If you really just have two possible values (e. g. 10 and 0), you can do it even simpler:



      my_list = [ 10 if i % (n+m) < n else 0 for i in range(95) ]


      But that iterates in Python over the whole range of 95, so probably is not very fast.



      A bit more complex but probably more efficient (especially for huge lists and large values for n and m) would be this:



      my_list = (([ 10 ] * n + [ 0 ] * m) * (95 // (n + m) + 1))[:95]


      But it builds internally lots of lists, so its up to tests to find out whether this is efficient in your case. (Also memory consumption should be taken into account for large lists.)



      If you can use numpy (a bit off the question, but since it's widespread):



      my_list = (np.arange(95) % (n+m) < n) * 10





      share|improve this answer














      my_list = [10] * 95
      n = 3
      m = 2
      for i in range(m):
      my_list[n+i::m+n] = [0] * len(my_list[n+i::m+n])


      This just needs m assignments to do the job (and m probably is small).



      If you really just have two possible values (e. g. 10 and 0), you can do it even simpler:



      my_list = [ 10 if i % (n+m) < n else 0 for i in range(95) ]


      But that iterates in Python over the whole range of 95, so probably is not very fast.



      A bit more complex but probably more efficient (especially for huge lists and large values for n and m) would be this:



      my_list = (([ 10 ] * n + [ 0 ] * m) * (95 // (n + m) + 1))[:95]


      But it builds internally lots of lists, so its up to tests to find out whether this is efficient in your case. (Also memory consumption should be taken into account for large lists.)



      If you can use numpy (a bit off the question, but since it's widespread):



      my_list = (np.arange(95) % (n+m) < n) * 10






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Sep 25 at 10:45

























      answered Sep 25 at 8:22









      Alfe

      29.9k106098




      29.9k106098











      • Could you post your 3 different solutions as 3 separate answers, please? I want to upvote the 2nd one, but the others... not so much.
        – Aran-Fey
        Sep 25 at 8:43






      • 3




        @Aran-Fey That would be overkill, I guess. Feel free to not upvote in this case, even if an upvote just states that the answer provided any help (not was perfect). And consider that the second one is probably the slowest of the four (only relevant for large numbers of course).
        – Alfe
        Sep 25 at 10:47
















      • Could you post your 3 different solutions as 3 separate answers, please? I want to upvote the 2nd one, but the others... not so much.
        – Aran-Fey
        Sep 25 at 8:43






      • 3




        @Aran-Fey That would be overkill, I guess. Feel free to not upvote in this case, even if an upvote just states that the answer provided any help (not was perfect). And consider that the second one is probably the slowest of the four (only relevant for large numbers of course).
        – Alfe
        Sep 25 at 10:47















      Could you post your 3 different solutions as 3 separate answers, please? I want to upvote the 2nd one, but the others... not so much.
      – Aran-Fey
      Sep 25 at 8:43




      Could you post your 3 different solutions as 3 separate answers, please? I want to upvote the 2nd one, but the others... not so much.
      – Aran-Fey
      Sep 25 at 8:43




      3




      3




      @Aran-Fey That would be overkill, I guess. Feel free to not upvote in this case, even if an upvote just states that the answer provided any help (not was perfect). And consider that the second one is probably the slowest of the four (only relevant for large numbers of course).
      – Alfe
      Sep 25 at 10:47




      @Aran-Fey That would be overkill, I guess. Feel free to not upvote in this case, even if an upvote just states that the answer provided any help (not was perfect). And consider that the second one is probably the slowest of the four (only relevant for large numbers of course).
      – Alfe
      Sep 25 at 10:47












      up vote
      27
      down vote













      You could use itertools.cycle to create an endless sequence of [10, 10, 10, 0, 0] and then take the first 95 elements of that sequence with itertools.islice:



      n = 3
      m = 2

      pattern = [10] * n + [0] * m
      my_list = list(itertools.islice(itertools.cycle(pattern), 95))





      share|improve this answer




















      • Why use itertools when you can use list expression?
        – Moonsik Park
        Sep 25 at 8:28






      • 5




        @MoonsikPark Not sure what you mean. If you're referring to your own solution: Because I think mine is more readable than yours.
        – Aran-Fey
        Sep 25 at 8:29














      up vote
      27
      down vote













      You could use itertools.cycle to create an endless sequence of [10, 10, 10, 0, 0] and then take the first 95 elements of that sequence with itertools.islice:



      n = 3
      m = 2

      pattern = [10] * n + [0] * m
      my_list = list(itertools.islice(itertools.cycle(pattern), 95))





      share|improve this answer




















      • Why use itertools when you can use list expression?
        – Moonsik Park
        Sep 25 at 8:28






      • 5




        @MoonsikPark Not sure what you mean. If you're referring to your own solution: Because I think mine is more readable than yours.
        – Aran-Fey
        Sep 25 at 8:29












      up vote
      27
      down vote










      up vote
      27
      down vote









      You could use itertools.cycle to create an endless sequence of [10, 10, 10, 0, 0] and then take the first 95 elements of that sequence with itertools.islice:



      n = 3
      m = 2

      pattern = [10] * n + [0] * m
      my_list = list(itertools.islice(itertools.cycle(pattern), 95))





      share|improve this answer












      You could use itertools.cycle to create an endless sequence of [10, 10, 10, 0, 0] and then take the first 95 elements of that sequence with itertools.islice:



      n = 3
      m = 2

      pattern = [10] * n + [0] * m
      my_list = list(itertools.islice(itertools.cycle(pattern), 95))






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Sep 25 at 8:27









      Aran-Fey

      20.4k53165




      20.4k53165











      • Why use itertools when you can use list expression?
        – Moonsik Park
        Sep 25 at 8:28






      • 5




        @MoonsikPark Not sure what you mean. If you're referring to your own solution: Because I think mine is more readable than yours.
        – Aran-Fey
        Sep 25 at 8:29
















      • Why use itertools when you can use list expression?
        – Moonsik Park
        Sep 25 at 8:28






      • 5




        @MoonsikPark Not sure what you mean. If you're referring to your own solution: Because I think mine is more readable than yours.
        – Aran-Fey
        Sep 25 at 8:29















      Why use itertools when you can use list expression?
      – Moonsik Park
      Sep 25 at 8:28




      Why use itertools when you can use list expression?
      – Moonsik Park
      Sep 25 at 8:28




      5




      5




      @MoonsikPark Not sure what you mean. If you're referring to your own solution: Because I think mine is more readable than yours.
      – Aran-Fey
      Sep 25 at 8:29




      @MoonsikPark Not sure what you mean. If you're referring to your own solution: Because I think mine is more readable than yours.
      – Aran-Fey
      Sep 25 at 8:29










      up vote
      7
      down vote













      Yet another possibility, this time with enumerate:



      [x * (i % (n + m) < n) for i, x in enumerate(my_list)]


      It uses the fact that False and True are equal to 0 and 1 in Python (see here).



      As a bonus, it works fine even if the list isn't constant:



      >>> n = 4
      >>> m = 2
      >>> my_list = range(20)
      >>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
      [0, 1, 2, 3, 0, 0, 6, 7, 8, 9, 0, 0, 12, 13, 14, 15, 0, 0, 18, 19]


      If the list contains strings, it replaces them with an empty string instead of 0:



      >>> my_list = 'abcdefghijk'
      >>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
      ['a', 'b', 'c', 'd', '', '', 'g', 'h', 'i', 'j', '']





      share|improve this answer
























        up vote
        7
        down vote













        Yet another possibility, this time with enumerate:



        [x * (i % (n + m) < n) for i, x in enumerate(my_list)]


        It uses the fact that False and True are equal to 0 and 1 in Python (see here).



        As a bonus, it works fine even if the list isn't constant:



        >>> n = 4
        >>> m = 2
        >>> my_list = range(20)
        >>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
        [0, 1, 2, 3, 0, 0, 6, 7, 8, 9, 0, 0, 12, 13, 14, 15, 0, 0, 18, 19]


        If the list contains strings, it replaces them with an empty string instead of 0:



        >>> my_list = 'abcdefghijk'
        >>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
        ['a', 'b', 'c', 'd', '', '', 'g', 'h', 'i', 'j', '']





        share|improve this answer






















          up vote
          7
          down vote










          up vote
          7
          down vote









          Yet another possibility, this time with enumerate:



          [x * (i % (n + m) < n) for i, x in enumerate(my_list)]


          It uses the fact that False and True are equal to 0 and 1 in Python (see here).



          As a bonus, it works fine even if the list isn't constant:



          >>> n = 4
          >>> m = 2
          >>> my_list = range(20)
          >>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
          [0, 1, 2, 3, 0, 0, 6, 7, 8, 9, 0, 0, 12, 13, 14, 15, 0, 0, 18, 19]


          If the list contains strings, it replaces them with an empty string instead of 0:



          >>> my_list = 'abcdefghijk'
          >>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
          ['a', 'b', 'c', 'd', '', '', 'g', 'h', 'i', 'j', '']





          share|improve this answer












          Yet another possibility, this time with enumerate:



          [x * (i % (n + m) < n) for i, x in enumerate(my_list)]


          It uses the fact that False and True are equal to 0 and 1 in Python (see here).



          As a bonus, it works fine even if the list isn't constant:



          >>> n = 4
          >>> m = 2
          >>> my_list = range(20)
          >>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
          [0, 1, 2, 3, 0, 0, 6, 7, 8, 9, 0, 0, 12, 13, 14, 15, 0, 0, 18, 19]


          If the list contains strings, it replaces them with an empty string instead of 0:



          >>> my_list = 'abcdefghijk'
          >>> [x * (i % (n+m) < n) for i, x in enumerate(my_list)]
          ['a', 'b', 'c', 'd', '', '', 'g', 'h', 'i', 'j', '']






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Sep 25 at 11:51









          Eric Duminil

          38.5k53064




          38.5k53064




















              up vote
              6
              down vote













              This worked for me:



              list = [10] * 95

              n = 4
              m = 2

              amask = np.tile(np.concatenate((np.ones(n),np.zeros(m))),int((len(list)+1)/(n+m)))[:len(list)]

              list = np.asarray(list)*amask


              which outputs:



              array([10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
              10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10.,
              10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10.,
              10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10.,
              0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0.,
              0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0.,
              10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
              10., 10., 10., 0.])


              The code takes n and m and constructs a mask of ones and zeros with a length matching your initial list using the np.tile function. Afterwards you just multiply the mask onto the list and get the zeros where you want them to be. It should also be flexibel to different lengths of the list and an (almost) arbitrary choice of n and m.



              You can cast the array back to a list if you want.






              share|improve this answer


















              • 1




                numpy? For real?
                – Alfe
                Sep 25 at 8:19






              • 1




                @Alfe: What's the problem with numpy? It's widespread and it's specifically designed for lists/arrays.
                – Eric Duminil
                Sep 25 at 9:51










              • @EricDuminil Just overkill for the job, that's all. It's like asking for a print() and getting a f=open('/dev/stdout', 'w'); f.write("foo"); f.flush(); f.close(). Works, yeah. But adds unnecessary complexity.
                – Alfe
                Sep 25 at 10:41







              • 1




                Btw, in numpy, I would have done it as (np.arange(95) % 5 < 3) * 10.
                – Alfe
                Sep 25 at 10:44






              • 3




                @Alfe Indeed, your accepted version is much more elegant -> +1. But nevertheless my suggestion also gets the job done and sometimes that's all you need. Thanks for pointing it out though.
                – Shintlor
                Sep 25 at 12:19














              up vote
              6
              down vote













              This worked for me:



              list = [10] * 95

              n = 4
              m = 2

              amask = np.tile(np.concatenate((np.ones(n),np.zeros(m))),int((len(list)+1)/(n+m)))[:len(list)]

              list = np.asarray(list)*amask


              which outputs:



              array([10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
              10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10.,
              10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10.,
              10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10.,
              0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0.,
              0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0.,
              10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
              10., 10., 10., 0.])


              The code takes n and m and constructs a mask of ones and zeros with a length matching your initial list using the np.tile function. Afterwards you just multiply the mask onto the list and get the zeros where you want them to be. It should also be flexibel to different lengths of the list and an (almost) arbitrary choice of n and m.



              You can cast the array back to a list if you want.






              share|improve this answer


















              • 1




                numpy? For real?
                – Alfe
                Sep 25 at 8:19






              • 1




                @Alfe: What's the problem with numpy? It's widespread and it's specifically designed for lists/arrays.
                – Eric Duminil
                Sep 25 at 9:51










              • @EricDuminil Just overkill for the job, that's all. It's like asking for a print() and getting a f=open('/dev/stdout', 'w'); f.write("foo"); f.flush(); f.close(). Works, yeah. But adds unnecessary complexity.
                – Alfe
                Sep 25 at 10:41







              • 1




                Btw, in numpy, I would have done it as (np.arange(95) % 5 < 3) * 10.
                – Alfe
                Sep 25 at 10:44






              • 3




                @Alfe Indeed, your accepted version is much more elegant -> +1. But nevertheless my suggestion also gets the job done and sometimes that's all you need. Thanks for pointing it out though.
                – Shintlor
                Sep 25 at 12:19












              up vote
              6
              down vote










              up vote
              6
              down vote









              This worked for me:



              list = [10] * 95

              n = 4
              m = 2

              amask = np.tile(np.concatenate((np.ones(n),np.zeros(m))),int((len(list)+1)/(n+m)))[:len(list)]

              list = np.asarray(list)*amask


              which outputs:



              array([10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
              10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10.,
              10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10.,
              10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10.,
              0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0.,
              0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0.,
              10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
              10., 10., 10., 0.])


              The code takes n and m and constructs a mask of ones and zeros with a length matching your initial list using the np.tile function. Afterwards you just multiply the mask onto the list and get the zeros where you want them to be. It should also be flexibel to different lengths of the list and an (almost) arbitrary choice of n and m.



              You can cast the array back to a list if you want.






              share|improve this answer














              This worked for me:



              list = [10] * 95

              n = 4
              m = 2

              amask = np.tile(np.concatenate((np.ones(n),np.zeros(m))),int((len(list)+1)/(n+m)))[:len(list)]

              list = np.asarray(list)*amask


              which outputs:



              array([10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
              10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10.,
              10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10.,
              10., 0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10.,
              0., 0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0.,
              0., 10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0.,
              10., 10., 10., 10., 0., 0., 10., 10., 10., 10., 0., 0., 10.,
              10., 10., 10., 0.])


              The code takes n and m and constructs a mask of ones and zeros with a length matching your initial list using the np.tile function. Afterwards you just multiply the mask onto the list and get the zeros where you want them to be. It should also be flexibel to different lengths of the list and an (almost) arbitrary choice of n and m.



              You can cast the array back to a list if you want.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Sep 25 at 8:21

























              answered Sep 25 at 8:17









              Shintlor

              35919




              35919







              • 1




                numpy? For real?
                – Alfe
                Sep 25 at 8:19






              • 1




                @Alfe: What's the problem with numpy? It's widespread and it's specifically designed for lists/arrays.
                – Eric Duminil
                Sep 25 at 9:51










              • @EricDuminil Just overkill for the job, that's all. It's like asking for a print() and getting a f=open('/dev/stdout', 'w'); f.write("foo"); f.flush(); f.close(). Works, yeah. But adds unnecessary complexity.
                – Alfe
                Sep 25 at 10:41







              • 1




                Btw, in numpy, I would have done it as (np.arange(95) % 5 < 3) * 10.
                – Alfe
                Sep 25 at 10:44






              • 3




                @Alfe Indeed, your accepted version is much more elegant -> +1. But nevertheless my suggestion also gets the job done and sometimes that's all you need. Thanks for pointing it out though.
                – Shintlor
                Sep 25 at 12:19












              • 1




                numpy? For real?
                – Alfe
                Sep 25 at 8:19






              • 1




                @Alfe: What's the problem with numpy? It's widespread and it's specifically designed for lists/arrays.
                – Eric Duminil
                Sep 25 at 9:51










              • @EricDuminil Just overkill for the job, that's all. It's like asking for a print() and getting a f=open('/dev/stdout', 'w'); f.write("foo"); f.flush(); f.close(). Works, yeah. But adds unnecessary complexity.
                – Alfe
                Sep 25 at 10:41







              • 1




                Btw, in numpy, I would have done it as (np.arange(95) % 5 < 3) * 10.
                – Alfe
                Sep 25 at 10:44






              • 3




                @Alfe Indeed, your accepted version is much more elegant -> +1. But nevertheless my suggestion also gets the job done and sometimes that's all you need. Thanks for pointing it out though.
                – Shintlor
                Sep 25 at 12:19







              1




              1




              numpy? For real?
              – Alfe
              Sep 25 at 8:19




              numpy? For real?
              – Alfe
              Sep 25 at 8:19




              1




              1




              @Alfe: What's the problem with numpy? It's widespread and it's specifically designed for lists/arrays.
              – Eric Duminil
              Sep 25 at 9:51




              @Alfe: What's the problem with numpy? It's widespread and it's specifically designed for lists/arrays.
              – Eric Duminil
              Sep 25 at 9:51












              @EricDuminil Just overkill for the job, that's all. It's like asking for a print() and getting a f=open('/dev/stdout', 'w'); f.write("foo"); f.flush(); f.close(). Works, yeah. But adds unnecessary complexity.
              – Alfe
              Sep 25 at 10:41





              @EricDuminil Just overkill for the job, that's all. It's like asking for a print() and getting a f=open('/dev/stdout', 'w'); f.write("foo"); f.flush(); f.close(). Works, yeah. But adds unnecessary complexity.
              – Alfe
              Sep 25 at 10:41





              1




              1




              Btw, in numpy, I would have done it as (np.arange(95) % 5 < 3) * 10.
              – Alfe
              Sep 25 at 10:44




              Btw, in numpy, I would have done it as (np.arange(95) % 5 < 3) * 10.
              – Alfe
              Sep 25 at 10:44




              3




              3




              @Alfe Indeed, your accepted version is much more elegant -> +1. But nevertheless my suggestion also gets the job done and sometimes that's all you need. Thanks for pointing it out though.
              – Shintlor
              Sep 25 at 12:19




              @Alfe Indeed, your accepted version is much more elegant -> +1. But nevertheless my suggestion also gets the job done and sometimes that's all you need. Thanks for pointing it out though.
              – Shintlor
              Sep 25 at 12:19










              up vote
              4
              down vote













              How about this?



              my_list = [10] * 95
              n = 3
              m = 2

              for i in range(n, len(my_list)-1, n+m):
              my_list[i:i+m] = [0]*m

              print(my_list)



              Edit



              I found out that the above code changes the length of resulting list in some cases.



              >>> a = [1,2,3]
              >>> a[2:4] = [0] * 2
              >>> a
              [1, 2, 0, 0]


              Thus, the length should be restored somehow.



              my_list = [10] * 95
              cp_list = list(my_list)
              n = 3
              m = 5

              for i in range(n, len(my_list)-1, n+m):
              cp_list[i:i+m] = [0]*m

              cp_list = cp_list[:len(my_list)]
              print(cp_list)





              share|improve this answer


















              • 1




                Nice approach. But only if len(my_list) is smaller than m, this is more efficient than my solution.
                – Alfe
                Sep 25 at 8:24






              • 1




                There is a downvote on this answer but no critic comment. Downvoter, please comment on what you didn't like.
                – Alfe
                Sep 25 at 8:29






              • 2




                For deleting the last elements of a list, best use del cp_list[n:].
                – Alfe
                Sep 25 at 14:58














              up vote
              4
              down vote













              How about this?



              my_list = [10] * 95
              n = 3
              m = 2

              for i in range(n, len(my_list)-1, n+m):
              my_list[i:i+m] = [0]*m

              print(my_list)



              Edit



              I found out that the above code changes the length of resulting list in some cases.



              >>> a = [1,2,3]
              >>> a[2:4] = [0] * 2
              >>> a
              [1, 2, 0, 0]


              Thus, the length should be restored somehow.



              my_list = [10] * 95
              cp_list = list(my_list)
              n = 3
              m = 5

              for i in range(n, len(my_list)-1, n+m):
              cp_list[i:i+m] = [0]*m

              cp_list = cp_list[:len(my_list)]
              print(cp_list)





              share|improve this answer


















              • 1




                Nice approach. But only if len(my_list) is smaller than m, this is more efficient than my solution.
                – Alfe
                Sep 25 at 8:24






              • 1




                There is a downvote on this answer but no critic comment. Downvoter, please comment on what you didn't like.
                – Alfe
                Sep 25 at 8:29






              • 2




                For deleting the last elements of a list, best use del cp_list[n:].
                – Alfe
                Sep 25 at 14:58












              up vote
              4
              down vote










              up vote
              4
              down vote









              How about this?



              my_list = [10] * 95
              n = 3
              m = 2

              for i in range(n, len(my_list)-1, n+m):
              my_list[i:i+m] = [0]*m

              print(my_list)



              Edit



              I found out that the above code changes the length of resulting list in some cases.



              >>> a = [1,2,3]
              >>> a[2:4] = [0] * 2
              >>> a
              [1, 2, 0, 0]


              Thus, the length should be restored somehow.



              my_list = [10] * 95
              cp_list = list(my_list)
              n = 3
              m = 5

              for i in range(n, len(my_list)-1, n+m):
              cp_list[i:i+m] = [0]*m

              cp_list = cp_list[:len(my_list)]
              print(cp_list)





              share|improve this answer














              How about this?



              my_list = [10] * 95
              n = 3
              m = 2

              for i in range(n, len(my_list)-1, n+m):
              my_list[i:i+m] = [0]*m

              print(my_list)



              Edit



              I found out that the above code changes the length of resulting list in some cases.



              >>> a = [1,2,3]
              >>> a[2:4] = [0] * 2
              >>> a
              [1, 2, 0, 0]


              Thus, the length should be restored somehow.



              my_list = [10] * 95
              cp_list = list(my_list)
              n = 3
              m = 5

              for i in range(n, len(my_list)-1, n+m):
              cp_list[i:i+m] = [0]*m

              cp_list = cp_list[:len(my_list)]
              print(cp_list)






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Sep 25 at 8:33

























              answered Sep 25 at 8:18









              klim

              51239




              51239







              • 1




                Nice approach. But only if len(my_list) is smaller than m, this is more efficient than my solution.
                – Alfe
                Sep 25 at 8:24






              • 1




                There is a downvote on this answer but no critic comment. Downvoter, please comment on what you didn't like.
                – Alfe
                Sep 25 at 8:29






              • 2




                For deleting the last elements of a list, best use del cp_list[n:].
                – Alfe
                Sep 25 at 14:58












              • 1




                Nice approach. But only if len(my_list) is smaller than m, this is more efficient than my solution.
                – Alfe
                Sep 25 at 8:24






              • 1




                There is a downvote on this answer but no critic comment. Downvoter, please comment on what you didn't like.
                – Alfe
                Sep 25 at 8:29






              • 2




                For deleting the last elements of a list, best use del cp_list[n:].
                – Alfe
                Sep 25 at 14:58







              1




              1




              Nice approach. But only if len(my_list) is smaller than m, this is more efficient than my solution.
              – Alfe
              Sep 25 at 8:24




              Nice approach. But only if len(my_list) is smaller than m, this is more efficient than my solution.
              – Alfe
              Sep 25 at 8:24




              1




              1




              There is a downvote on this answer but no critic comment. Downvoter, please comment on what you didn't like.
              – Alfe
              Sep 25 at 8:29




              There is a downvote on this answer but no critic comment. Downvoter, please comment on what you didn't like.
              – Alfe
              Sep 25 at 8:29




              2




              2




              For deleting the last elements of a list, best use del cp_list[n:].
              – Alfe
              Sep 25 at 14:58




              For deleting the last elements of a list, best use del cp_list[n:].
              – Alfe
              Sep 25 at 14:58










              up vote
              3
              down vote













              numpy can do this pretty concisely, too!



              a = np.array(my_list).reshape(-1, n + m)
              a[:, n:] = 0
              result = a.ravel().tolist()





              share|improve this answer
















              • 2




                It doesn't seem to work with n = 4 and m = 2. It raises ValueError: cannot reshape array of size 95 into shape (6).
                – Eric Duminil
                Sep 25 at 9:57










              • @EricDuminil shouldn't an error be raised if the length of the original list is not a multiple of the length of the subsequences to be repeated?
                – timgeb
                Sep 25 at 10:02











              • Please take a look at the second half of the question. This use case is specifically mentioned by OP.
                – Eric Duminil
                Sep 25 at 10:03






              • 3




                @EricDuminil you are right. This answer does not work in the latter case.
                – timgeb
                Sep 25 at 10:05














              up vote
              3
              down vote













              numpy can do this pretty concisely, too!



              a = np.array(my_list).reshape(-1, n + m)
              a[:, n:] = 0
              result = a.ravel().tolist()





              share|improve this answer
















              • 2




                It doesn't seem to work with n = 4 and m = 2. It raises ValueError: cannot reshape array of size 95 into shape (6).
                – Eric Duminil
                Sep 25 at 9:57










              • @EricDuminil shouldn't an error be raised if the length of the original list is not a multiple of the length of the subsequences to be repeated?
                – timgeb
                Sep 25 at 10:02











              • Please take a look at the second half of the question. This use case is specifically mentioned by OP.
                – Eric Duminil
                Sep 25 at 10:03






              • 3




                @EricDuminil you are right. This answer does not work in the latter case.
                – timgeb
                Sep 25 at 10:05












              up vote
              3
              down vote










              up vote
              3
              down vote









              numpy can do this pretty concisely, too!



              a = np.array(my_list).reshape(-1, n + m)
              a[:, n:] = 0
              result = a.ravel().tolist()





              share|improve this answer












              numpy can do this pretty concisely, too!



              a = np.array(my_list).reshape(-1, n + m)
              a[:, n:] = 0
              result = a.ravel().tolist()






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Sep 25 at 8:42









              timgeb

              37.5k104875




              37.5k104875







              • 2




                It doesn't seem to work with n = 4 and m = 2. It raises ValueError: cannot reshape array of size 95 into shape (6).
                – Eric Duminil
                Sep 25 at 9:57










              • @EricDuminil shouldn't an error be raised if the length of the original list is not a multiple of the length of the subsequences to be repeated?
                – timgeb
                Sep 25 at 10:02











              • Please take a look at the second half of the question. This use case is specifically mentioned by OP.
                – Eric Duminil
                Sep 25 at 10:03






              • 3




                @EricDuminil you are right. This answer does not work in the latter case.
                – timgeb
                Sep 25 at 10:05












              • 2




                It doesn't seem to work with n = 4 and m = 2. It raises ValueError: cannot reshape array of size 95 into shape (6).
                – Eric Duminil
                Sep 25 at 9:57










              • @EricDuminil shouldn't an error be raised if the length of the original list is not a multiple of the length of the subsequences to be repeated?
                – timgeb
                Sep 25 at 10:02











              • Please take a look at the second half of the question. This use case is specifically mentioned by OP.
                – Eric Duminil
                Sep 25 at 10:03






              • 3




                @EricDuminil you are right. This answer does not work in the latter case.
                – timgeb
                Sep 25 at 10:05







              2




              2




              It doesn't seem to work with n = 4 and m = 2. It raises ValueError: cannot reshape array of size 95 into shape (6).
              – Eric Duminil
              Sep 25 at 9:57




              It doesn't seem to work with n = 4 and m = 2. It raises ValueError: cannot reshape array of size 95 into shape (6).
              – Eric Duminil
              Sep 25 at 9:57












              @EricDuminil shouldn't an error be raised if the length of the original list is not a multiple of the length of the subsequences to be repeated?
              – timgeb
              Sep 25 at 10:02





              @EricDuminil shouldn't an error be raised if the length of the original list is not a multiple of the length of the subsequences to be repeated?
              – timgeb
              Sep 25 at 10:02













              Please take a look at the second half of the question. This use case is specifically mentioned by OP.
              – Eric Duminil
              Sep 25 at 10:03




              Please take a look at the second half of the question. This use case is specifically mentioned by OP.
              – Eric Duminil
              Sep 25 at 10:03




              3




              3




              @EricDuminil you are right. This answer does not work in the latter case.
              – timgeb
              Sep 25 at 10:05




              @EricDuminil you are right. This answer does not work in the latter case.
              – timgeb
              Sep 25 at 10:05










              up vote
              3
              down vote













              [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]


              Maybe?



              Result



              >>> num, input_num, m, n=95, 10, 2, 3
              >>> [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
              [10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0 , 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0]





              share|improve this answer


















              • 3




                I guess the list full of 10 is just for an example...
                – Julien
                Sep 25 at 8:07










              • @Julien No, OP said ' it can be any number, but it will always be the same one' so it will be full of any same number.
                – Moonsik Park
                Sep 25 at 8:20







              • 1




                1) Your output is incorrect (it's [10, 10, 0, 0, 0] instead of [10, 10, 10, 0, 0]) 2) Concatenating lists with sum is an antipattern with a massive run time complexity.
                – Aran-Fey
                Sep 25 at 8:34










              • @Aran-Fey Nope, it's correct.
                – Moonsik Park
                Sep 25 at 8:39










              • Oops. Indeed it is. Edited.
                – Moonsik Park
                Sep 25 at 8:44














              up vote
              3
              down vote













              [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]


              Maybe?



              Result



              >>> num, input_num, m, n=95, 10, 2, 3
              >>> [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
              [10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0 , 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0]





              share|improve this answer


















              • 3




                I guess the list full of 10 is just for an example...
                – Julien
                Sep 25 at 8:07










              • @Julien No, OP said ' it can be any number, but it will always be the same one' so it will be full of any same number.
                – Moonsik Park
                Sep 25 at 8:20







              • 1




                1) Your output is incorrect (it's [10, 10, 0, 0, 0] instead of [10, 10, 10, 0, 0]) 2) Concatenating lists with sum is an antipattern with a massive run time complexity.
                – Aran-Fey
                Sep 25 at 8:34










              • @Aran-Fey Nope, it's correct.
                – Moonsik Park
                Sep 25 at 8:39










              • Oops. Indeed it is. Edited.
                – Moonsik Park
                Sep 25 at 8:44












              up vote
              3
              down vote










              up vote
              3
              down vote









              [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]


              Maybe?



              Result



              >>> num, input_num, m, n=95, 10, 2, 3
              >>> [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
              [10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0 , 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0]





              share|improve this answer














              [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]


              Maybe?



              Result



              >>> num, input_num, m, n=95, 10, 2, 3
              >>> [j for i in [[input_num] * n + [0] * m for x in range(int(num / (m + n)) + 1)][:num] for j in i]
              [10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0, 10, 10, 10, 0 , 0, 10, 10, 10, 0, 0, 10, 10, 10, 0, 0]






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Sep 25 at 8:45









              Aran-Fey

              20.4k53165




              20.4k53165










              answered Sep 25 at 8:06









              Moonsik Park

              4594




              4594







              • 3




                I guess the list full of 10 is just for an example...
                – Julien
                Sep 25 at 8:07










              • @Julien No, OP said ' it can be any number, but it will always be the same one' so it will be full of any same number.
                – Moonsik Park
                Sep 25 at 8:20







              • 1




                1) Your output is incorrect (it's [10, 10, 0, 0, 0] instead of [10, 10, 10, 0, 0]) 2) Concatenating lists with sum is an antipattern with a massive run time complexity.
                – Aran-Fey
                Sep 25 at 8:34










              • @Aran-Fey Nope, it's correct.
                – Moonsik Park
                Sep 25 at 8:39










              • Oops. Indeed it is. Edited.
                – Moonsik Park
                Sep 25 at 8:44












              • 3




                I guess the list full of 10 is just for an example...
                – Julien
                Sep 25 at 8:07










              • @Julien No, OP said ' it can be any number, but it will always be the same one' so it will be full of any same number.
                – Moonsik Park
                Sep 25 at 8:20







              • 1




                1) Your output is incorrect (it's [10, 10, 0, 0, 0] instead of [10, 10, 10, 0, 0]) 2) Concatenating lists with sum is an antipattern with a massive run time complexity.
                – Aran-Fey
                Sep 25 at 8:34










              • @Aran-Fey Nope, it's correct.
                – Moonsik Park
                Sep 25 at 8:39










              • Oops. Indeed it is. Edited.
                – Moonsik Park
                Sep 25 at 8:44







              3




              3




              I guess the list full of 10 is just for an example...
              – Julien
              Sep 25 at 8:07




              I guess the list full of 10 is just for an example...
              – Julien
              Sep 25 at 8:07












              @Julien No, OP said ' it can be any number, but it will always be the same one' so it will be full of any same number.
              – Moonsik Park
              Sep 25 at 8:20





              @Julien No, OP said ' it can be any number, but it will always be the same one' so it will be full of any same number.
              – Moonsik Park
              Sep 25 at 8:20





              1




              1




              1) Your output is incorrect (it's [10, 10, 0, 0, 0] instead of [10, 10, 10, 0, 0]) 2) Concatenating lists with sum is an antipattern with a massive run time complexity.
              – Aran-Fey
              Sep 25 at 8:34




              1) Your output is incorrect (it's [10, 10, 0, 0, 0] instead of [10, 10, 10, 0, 0]) 2) Concatenating lists with sum is an antipattern with a massive run time complexity.
              – Aran-Fey
              Sep 25 at 8:34












              @Aran-Fey Nope, it's correct.
              – Moonsik Park
              Sep 25 at 8:39




              @Aran-Fey Nope, it's correct.
              – Moonsik Park
              Sep 25 at 8:39












              Oops. Indeed it is. Edited.
              – Moonsik Park
              Sep 25 at 8:44




              Oops. Indeed it is. Edited.
              – Moonsik Park
              Sep 25 at 8:44










              up vote
              0
              down vote













              Also in the itertools family, you can repeat a desired pattern:



              Given



              import itertools as it


              m, n = 2, 3
              p = n + 1


              Code



              pattern = it.repeat([10] * n + [0] * m)
              res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
              print(res)
              # [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0, 0]




              pattern = it.repeat([10] * p + [0] * m)
              res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
              print(res)
              # [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0]


              Test



              assert len(res) == 95


              However, @Aran-Fey's itertools.cycle solution is cleaner as it does not require chaining.






              share|improve this answer
























                up vote
                0
                down vote













                Also in the itertools family, you can repeat a desired pattern:



                Given



                import itertools as it


                m, n = 2, 3
                p = n + 1


                Code



                pattern = it.repeat([10] * n + [0] * m)
                res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
                print(res)
                # [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0, 0]




                pattern = it.repeat([10] * p + [0] * m)
                res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
                print(res)
                # [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0]


                Test



                assert len(res) == 95


                However, @Aran-Fey's itertools.cycle solution is cleaner as it does not require chaining.






                share|improve this answer






















                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  Also in the itertools family, you can repeat a desired pattern:



                  Given



                  import itertools as it


                  m, n = 2, 3
                  p = n + 1


                  Code



                  pattern = it.repeat([10] * n + [0] * m)
                  res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
                  print(res)
                  # [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0, 0]




                  pattern = it.repeat([10] * p + [0] * m)
                  res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
                  print(res)
                  # [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0]


                  Test



                  assert len(res) == 95


                  However, @Aran-Fey's itertools.cycle solution is cleaner as it does not require chaining.






                  share|improve this answer












                  Also in the itertools family, you can repeat a desired pattern:



                  Given



                  import itertools as it


                  m, n = 2, 3
                  p = n + 1


                  Code



                  pattern = it.repeat([10] * n + [0] * m)
                  res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
                  print(res)
                  # [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0, 0]




                  pattern = it.repeat([10] * p + [0] * m)
                  res = list(it.islice(it.chain.from_iterable(pattern), None, 95))
                  print(res)
                  # [10, 10, 10, 10, 0, 0, 10, 10, 10, 10, 0, 0, ... 10, 10, 10, 10, 0]


                  Test



                  assert len(res) == 95


                  However, @Aran-Fey's itertools.cycle solution is cleaner as it does not require chaining.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 2 days ago









                  pylang

                  12k23349




                  12k23349



























                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52493328%2fperiodically-replacing-values-in-a-list%23new-answer', 'question_page');

                      );

                      Post as a guest













































































                      Popular posts from this blog

                      How to check contact read email or not when send email to Individual?

                      Bahrain

                      Postfix configuration issue with fips on centos 7; mailgun relay