0
class points():

  def __init__(self,a1,b1,c1,d1):
    self.a1=a1
    self.b1=b1
    self.c1=c1
    self.d1=d1


  def plot(self):
    xs=[self.a1[0],self.b1[0],self.c1[0],self.d1[0]]                           
    ys=[self.a1[1],self.b1[1],self.c1[1],self.d1[1]] 
    print(xs)
    print(ys)                           
    colors=['c','m','b','y']

a1=points([1,2],[2],[3,4],[4,5])
a1.plot()

How to define a default list so that when I am not providing value to b1[1] , it doesn't give error?

3
  • 1
    what do you want to fill if index does not exist ? Commented Sep 15, 2022 at 19:47
  • 1
    You can't. list doesn't have a counterpart to dict.get. Either validate that a correct list is assigned to self.b1 in the first place, or handle the possible IndexError in points.plot. Commented Sep 15, 2022 at 19:54
  • @DeepakTripathi any value I assign it to Commented Sep 15, 2022 at 19:59

2 Answers 2

1

this could be an option but I am not sure about the question.

class points():

  def __init__(self,a1,b1,c1,d1):
    self.a1=a1
    self.b1=b1
    self.c1=c1
    self.d1=d1


  def plot(self, default_val=0):
    elements = [self.a1,self.b1,self.c1,self.d1]
    xs=[val[0] if type(val) is list and len(val)>0 else default_val for val in elements]                           
    ys=[val[1] if type(val) is list and len(val)>1 else default_val for val in elements] 
    print(xs)
    print(ys)                           
    colors=['c','m','b','y']

a1=points([1,2],[2],[3,4],[4,5])
a1.plot()
>>>
[1, 2, 3, 4]
[2, 0, 4, 5]

a1.plot(14)
>>>
[1, 2, 3, 4]
[2, 14, 4, 5]
Sign up to request clarification or add additional context in comments.

Comments

1

You can try this hack as well

from collections import defaultdict
default_value = 0

class points():

  def __init__(self,a1,b1,c1,d1, default_value=default_value):
    self.b1=defaultdict(lambda : default_value, enumerate(b1))
    self.a1=defaultdict(lambda : default_value,enumerate(a1))
    self.c1=defaultdict(lambda : default_value,enumerate(c1))
    self.d1=defaultdict(lambda : default_value,enumerate(d1))


  def plot(self):
    xs=[self.a1[0],self.b1[0],self.c1[0],self.d1[0]]                           
    ys=[self.a1[1],self.b1[1],self.c1[1],self.d1[1]] 
    print(xs)
    print(ys)                           
    colors=['c','m','b','y']

a1=points([1,2],[2],[3,4],[4,5], default_value=default_value)
a1.plot()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.