Posts: 23
Threads: 13
Joined: Oct 2017
I want to produce the list: ["*", "*", "*", "*", "*"].
Can this be done in a simple line? (I don't want to have to create a function to do it.)
So far I have been having to do the following, which is very inconvenient and tedious:
v = []
for i in xrange(5):
v.append("*")
Posts: 12,043
Threads: 487
Joined: Sep 2016
Nov-21-2017, 10:51 PM
(This post was last modified: Nov-21-2017, 10:51 PM by Larz60+.)
v = ('* '*5).split() result:
Output: >>> v
['*', '*', '*', '*', '*']
Posts: 23
Threads: 13
Joined: Oct 2017
(Nov-21-2017, 10:51 PM)Larz60+ Wrote: v = ('* '*5).split() result:
Output: >>> v
['*', '*', '*', '*', '*']
Thanks. How come it doesn't work to then append to v?
So for example:
v = ('* '*5).split()
print v.append("*") gives an output of
Output: None
Posts: 7,324
Threads: 123
Joined: Sep 2016
You code as list comprehensions.
>>> v = ['*' for i in range(5)]
>>> v
['*', '*', '*', '*', '*'] Or:
>>> v = ['*'] * 5
>>> v
['*', '*', '*', '*', '*']
Posts: 12,043
Threads: 487
Joined: Sep 2016
I can do it with the one i wrote:
>>> v = ('* '*5).split()
>>> v
['*', '*', '*', '*', '*']
>>> v.append('-')
>>> v
['*', '*', '*', '*', '*', '-']
>>>
Posts: 3,458
Threads: 101
Joined: Sep 2016
list.append() will append the item, but it returns None. Since you're print() ing the return value of list.append(), that's why you see None.
Posts: 2,953
Threads: 48
Joined: Sep 2016
Nov-27-2017, 10:40 PM
(This post was last modified: Nov-27-2017, 10:40 PM by wavic.)
|