Home > other >  Creating an array as u =[0 n-1 n-2........1]
Creating an array as u =[0 n-1 n-2........1]

Time:11-27

u = []
n = 3
for i in range(0,n):
    u[i] = n - i
    u.append(u[i])
print(u)

I am creating an array as u = [0 n-2 n-1....1]. I tried with above code and I cant find my mistake here.

CodePudding user response:

It seems you want to generate a list from 0 to n (or from n to 0)

You're pretty close. Easier would be to convert generator from range directly to list

n = 3
print(list(range(0, n)))  # [0, 1, 2]
# or for reversed
print(list(reversed(range(0, n))))  # [2, 1, 0]

CodePudding user response:

First, check if i == 0 then add to u list. Assign x from n subtracted by 1 and i. break if x is equal to 0 otherwise append x to u list.

u = []
n = 7
for i in range(n):
    if i == 0: u  = [i]
    x = n - 1 - i
    if x == 0: break
    u.append(x)

print(u)

# [0, 6, 5, 4, 3, 2, 1]
  • Related