Kevin Chan
Kevin Chan

Reputation: 85

Creating a list with n integers followed by an integer

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.

Upvotes: 1

Views: 173

Answers (5)

smac89
smac89

Reputation: 43254

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

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 114108

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))

Upvotes: 1

user2246674
user2246674

Reputation: 7719

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

Upvotes: 6

Ania Warzecha
Ania Warzecha

Reputation: 1796

It is as simple as:

[1] * n + [10]

Upvotes: 1

Gavin H
Gavin H

Reputation: 10502

Try the following:

n*[1] + [10]

Upvotes: 6

Related Questions