1

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.

Kevin Chan
  • 85
  • 1
  • 6

5 Answers5

6

Try the following:

n*[1] + [10]
Gavin H
  • 10,274
  • 3
  • 35
  • 42
6

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
user2246674
  • 7,621
  • 25
  • 28
1

It is as simple as:

[1] * n + [10]
Ania Warzecha
  • 1,796
  • 13
  • 26
1

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))
Joran Beasley
  • 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
0

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

Community
  • 1
  • 1
smac89
  • 39,374
  • 15
  • 132
  • 179