Charan
Charan

Reputation: 21

How to print all the values of the list?

I have a function which looks like thus class Data: def init(self, x, y): """ (Data, list, list) -> NoneType

    Create a new data object with two attributes: x and y.
    """
    self.x = x
    self.y = y

def num_obs(self):
    """ (Data) -> int

    Return the number of observations in the data set.

    >>> data = Data([1, 2], [3, 4])
    >>> data.num_obs()
    2
    """

    return len(self.x)

def __str__(self):
    """ (Data) -> str
    Return a string representation of this Data in this format:
    x               y
    18.000          120.000
    20.000          110.000
    22.000          120.000
    25.000          135.000
    26.000          140.000
    29.000          115.000
    30.000          150.000
    33.000          165.000
    33.000          160.000
    35.000          180.000
    """
    for i in range(len(self.x)):
        a = self.x[i]
    for i in range(len(self.y)):
        b = self.y[i]
    return ("x               y\n{0:.3f}         {1:.3f}".format(a,b))

When I call this function it returns only the last number of the list.

for example:

data = Data([18,20,22,25],[120,110,120,135])

print(data)

x y

25.000 135.000

I want it to return all the numbers

Upvotes: 0

Views: 149

Answers (2)

CypherX
CypherX

Reputation: 7353

Solution

Change the method __str__() into the following and it would work.

Changed made are:

  1. Use of zip(self.x, self.y) instead of range(len(self.x)).
  2. You were returning the last values of a and b in the string.
  3. What you needed instead is a string developed using a loop, where the a,b values get appended to the string in every iteration.
    def __str__(self):
        """ (Data) -> str
        Return a string representation of this Data in this format:
        x               y
        18.000          120.000
        20.000          110.000
        22.000          120.000
        25.000          135.000
        26.000          140.000
        29.000          115.000
        30.000          150.000
        33.000          165.000
        33.000          160.000
        35.000          180.000
        """
        s = "x               y"
        for a,b in zip(self.x, self.y): 
            s += "\n{0:.3f}         {1:.3f}".format(a,b)
        return s

Output:

data = Data([18,20,22,25],[120,110,120,135])
print(data)

x               y
18.000         120.000
20.000         110.000
22.000         120.000
25.000         135.000

Upvotes: 0

kaya3
kaya3

Reputation: 51034

Your question requires joining strings together; not printing them. You can use the join method with a generator expression:

    def __str__(self):
        return 'x               y\n' + '\n'.join(
            '{0:.3f}         {1:.3f}'.format(a, b)
            for a, b in zip(self.x, self.y)
        )

This uses zip as a simpler way to get pairs of numbers at the same index in self.x and self.y.

Upvotes: 2

Related Questions