#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    13
    Rep Power
    0

    Extending a list till it reaches a given size


    Hi all,

    Sorry for the nOOb question but I have been unsuccessfully trying to figure this out which should be simple.

    Is there an elegant way to do this:

    Code:
    a = [2, 2, 5]
    while len(a) < 6:
        a.extend([1])
    resulting in a = [2, 2, 5, 1, 1, 1]

    I was wondering if there is an awesome python feature that does it in the most beautiful way

    Thanks,
    Luca
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    438
    Rep Power
    67
    Originally Posted by pamparana
    I was wondering if there is an awesome python feature that does it in the most beautiful way
    How about:

    Code:
    >>> a = [2, 2, 5]
    >>> a + [1] * 3
    [2, 2, 5, 1, 1, 1]
    (Where the factor 3 could be calculated from the desired length minus the current length.)

    Comments on this post

    • pamparana agrees
    My armada: openSUSE 13.1 (home desktop, home laptop), Crunchbang Linux 11 (work laptop), Trisquel GNU/Linux 6.0.1 (mini laptop), Ubuntu 14.04 LTS (server), Android 4.2.1 (tablet), Windows 7 Ultimate (testbed)
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    13
    Rep Power
    0
    Elegant enough! Sold

    Many thanks!

IMN logo majestic logo threadwatch logo seochat tools logo