0

below are my codes

ls = np.repeat(4,5).tolist()
ls.append(100*3)

the output I get is as expected

[4, 4, 4, 4, 4, 300]

However when I do this

ls = np.repeat(4,5).tolist().append(100*3)

my "ls" is blank?? what am I doing wrong?

user13412850
  • 509
  • 1
  • 5
  • 16
  • 4
    `append` returns `None`, not the updated list. The list is modified in-place. Notice you didn't have to save the return value of `ls.append` in the first example; `ls` itself reflected the change. – chepner Mar 07 '22 at 14:24
  • 1
    ah yes I get it now! Now, is there a way to show "np.repeat(4,5).tolist().append(100*3)" in one line so that I get output ls = [4,4,4,4,400] ? – user13412850 Mar 07 '22 at 14:34
  • 1
    Yes, there is but you should not write it like that. Writing it in 2 different lines will give you cleaner code. – matszwecja Mar 07 '22 at 14:37
  • yeh agreed, just wanted to see if I could keep it in one line. as its part of a much larger code. – user13412850 Mar 07 '22 at 14:38
  • 2
    `(ls := np.repeat(4,5).tolist()).append(100*3)` is the one-liner but as mentioned, treat it as more of a brain-teaser than actual piece of code you should use. – matszwecja Mar 07 '22 at 14:39
  • no that didnt work (ls:= np.repeat(4,5).tolist()).append(100*3) File "", line 1 (ls:= np.repeat(4,5).tolist()).append(100*3) ^ SyntaxError: invalid syntax – user13412850 Mar 07 '22 at 14:43
  • Update your Python and it will work. (3.8+ specifically) – matszwecja Mar 07 '22 at 14:45
  • ok, i might I might just break it into two codes. thanks for the code though - good to know something like that exists! – user13412850 Mar 07 '22 at 14:47
  • 1
    You can also do `ls = np.append(np.repeat(4,5), 100*3).tolist()` for a one-line solution using `np.append`, but as others have suggested fewer lines do not necessarily mean better code. – H_Boofer Mar 07 '22 at 14:54
  • great! thanks that was helpful as well. – user13412850 Mar 07 '22 at 15:00

0 Answers0