I'm trying to generate this list:

["var",None,None,None,None,None]

What's the short way to do this? I thought

list_2=["var",None for cnt in range(5)]

would work but it just generates an error. My second attempt,

list_1=["var"].extend([None for cnt in range(5)])

wasn't exactly a success story either. Could anyone please help?

Thank you!

有帮助吗?

解决方案

This can simply be done as

mylist = ["var"] + [None] * 5

The Reason,

["var"].extend([None for cnt in range(5)])

will not work, because extends changes the list in-place, but does not return the original list. You could have done

mylist = ["var"]
mylist.extend([None for cnt in range(5)])

Your second attempt

list_2=["var",None for cnt in range(5)]

is also not correct

  1. Because its a generator expression without parenthesis.
  2. Even if it would have worked, it would add what ever you get as the second item in the list

其他提示

You can do it this way:

>>> list_1 = ["var"] + [None]*5
>>> list_1
['var', None, None, None, None, None]

Python 3.2

a=["var"]
_=[a.append(None)for v in range(5)] 

another way with extend:

a=["var"]
b=[None]*5
a.extend(b)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top