I need to create a list with n indices of 1 followed by a 10 all in a single line of code (it has to be submitted online on a single line). I tried: (n*[1]).append(10)
but that returns a None type. Is this doable? Thanks.

- 85
- 1
- 6
5 Answers
Try the following:
n*[1] + [10]

- 10,274
- 3
- 35
- 42
-
Ahhhh... I way over complicated that. Thank you. – Kevin Chan Sep 20 '13 at 22:54
Python methods that cause side-effects (read: mutate the object) often evaluate to None
- which is to reinforce the fact that they exist to cause such side-effects (read: object mutations). list.append
is one such example of this pattern (although another good example is list.sort
vs sorted
).
Compare the usage in the question with:
l = n * [1]
l.append(10) # returns None ..
print l # .. but list was mutated

- 7,621
- 25
- 28
-
2+1 for the explanation of why OP got `None`. We need more of this on SO, instead of giving other solutions – TerryA Sep 20 '13 at 23:19
-
@Haidro Thanks! I think it's important to find/explore a combination between the two, but didn't want to repeat the other answers :D – user2246674 Sep 20 '13 at 23:20
-
Sometimes I come to answer, and end up learning something. Thanks! – CamelopardalisRex Sep 20 '13 at 23:46
alternatively, use a list comprehension
n=10
[1 if i < n else 10 for i in range(n+1)]
#or a map (although depending on python version it may return a generator)
map(lambda x:1 if x < n else 10,range(n+1))

- 110,522
- 12
- 160
- 179
-
I think this will give a result that has one too few `1`s in it. You'd want `if i < n` and `range(n+1)`, I think. – Blckknght Sep 20 '13 at 23:22
What about:
[1 for _ in range(n)] + [10]
Reason I didn't use the n * [1] + [10]
method is not only because it has been submitted, but also because in the case where the object you want to spread across the list is mutable; so for example you want to create a list of n
lists. If you use the n * [1] + [10]
method, each list in the list will refer to the same list. So when you operate on just one of the lists, all the other lists are affected as well.
Example
>>> list_of_lists = [[]] * 10
>>> list_of_lists[0].append(9)
>>> print list_of_lists
Output:
[[9], [9], [9], [9], [9], [9], [9], [9], [9], [9]]
See this question for why this happens