Martin
Martin

Reputation: 1

How to insert 2-d list?

Here is my source code I'm doing this without using import math

#2-d list append
n=int(input('enter final value'))
l=[]
for i in range(0,3):
    l[i]=[]
    if i==0:
        for x in range(0,n+1):
            if x%2==0:
                l[i].append(x)
    if i==1:
        for x in range(0,n+1):
            if x%2!=0:
                l[i].append(x)
    if i==2:
        for x in range(0,n+1) and x!=1:
            f=0
            a=int(n/2)
            for j in range(2,a):
                if x%j==0:
                    f+=1
            if(f==0):
                l[i].append(x)
     l.append(l[i])
 print(l)

it shows the following error:

Traceback (most recent call last):
  File "C:/Users/New/Desktop/py/2_D.py", line 5, in <module>
    l[i]=[]
IndexError: list assignment index out of range

I'd like to know how should I correct my code to be able to insert a 2-d list

Upvotes: 0

Views: 32

Answers (2)

DavidG
DavidG

Reputation: 25380

l is an empty list. You then try to assign an empty list to the first element of l, but it doesn't have a first element as it is empty. You probably want to append it instead using l.append([]).

Note, in the line:

for x in range(0,n+1) and x!=1:

The condition needs to go into an if statement on the next line and the code block after it indented appropriately.

n=int(input('enter final value'))
l=[]
for i in range(0,3):
    l.append([])   # append an empty list
    if i==0:
        for x in range(0,n+1):
            if x%2==0:
                l[i].append(x)
    if i==1:
        for x in range(0,n+1):
            if x%2!=0:
                l[i].append(x)
    if i==2:
        for x in range(0,n+1):
            if x!=1:   # Moved the if statement to a new line
                f=0
                a=int(n/2)
                for j in range(2,a):
                    if x%j==0:
                        f+=1
                if(f==0):
                    l[i].append(x)
    l.append(l[i])
print(l)

Upvotes: 1

mohamad jalali
mohamad jalali

Reputation: 372

write this line :

l.append([])

instead

l[i] =[]

when you write l[i] interpreter try to access l[0] but length of l is zero.

Upvotes: 0

Related Questions