Reputation: 612
At the moment I am trying to figure out how to solve a simple problem using List Comprehension. The point is to make a list and fill it with 1 at the beginning and at the end of the list. The rest elements are filled with 0.
I already tried the following:
desired_length = int(input('Enter the desired length: '))
list_=[0 if x==0 if x==desired_length-1 else x for x in range(desired_length)]
print(list_)
Edit Fixed the square brackets
And here is the code I am trying to convert:
def test():
desired_length = int(input('Enter the desired length: '))
list_ = []
for i in range(desired_length):
if i == 0 or i == desired_length - 1:
list_.append(1)
else:
list_.append(0)
print(list_)
Upvotes: 0
Views: 115
Reputation: 31
I'm using short-circuit expression here instead of ternary condition (just like Imtinan Azhar's answer)
[int(idx==0 or idx==desired_length - 1) for idx in range(desired_length)]
Upvotes: 0
Reputation: 27485
You have 2 very easy ways of achieving the result you want.
You could use the in
operator and since bool
Is a subset of int
Just cast it to int
:
list_ = [int(i in (0, desired_length - 1)) for i in range(desired_length)]
Or just using the star operator to unpack a list of zeros of length-2
And put 1
's at each end, no looping required
list_ = [1, *([0]*(desired_length-2)), 1]
Upvotes: 2
Reputation: 116
There is a simple way to do that. Here is my code:
def test():
desired_length = int(input('Enter the desired length: '))
list_ = [0]*desired_length
list_[0]=1
list_[-1]=1
I hope I helped!
Upvotes: 0
Reputation: 23815
Here
desired_length = int(input('Enter the desired length: '))
lst = [1 if idx == 0 or idx == desired_length-1 else 0 for idx,x in enumerate(range(desired_length))]
print(lst)
Upvotes: 0
Reputation: 1753
Firstly a dictionary is defined by {}
and a list by []
you are defining a dictionary not a list.
Secondly, this is what you want
[1 if (idx==0 or idx == (desired_length-1)) else 0 for idx in range(desired_length)]
what you are doing sets 1 at the start and end but 1,2,3 and so on in between
Thirdly, you have the condition set to put 0 at the start and end rather than 1.
Upvotes: 1
Reputation: 11228
using list comprehension
desired_length = int(input('Enter the desired length: '))
list_ = [(1 if i in [0,desired_length-1] else 0) for i in range(desired_length)]
print(list_)
output
Enter the desired length: 10
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1]
Upvotes: 0