1

As you see that the variable 'count' has an initial value of 0. This get overwritten by the another value when the loop is ran; lets say the new value is '8'. Then as the loop runs again the new value of '8' get overwritten by the newer value; lets say the new value is '5'. This means that value '8' is unrecoverable. I do not want to lose any of the values being created from the loop, but rather store them into list. How do i store the created values into a list?

Here is my code:

def printTable(items):
    for i in  range (len(items[0])):
        print ()
        counter = 0
        for j in range(len(items)):
            if len(items[i][j]) > counter:                count = len(items[i][j])
                itemName = items[i][j]
        print ('the longest string is: ' + itemName + '; and its length is ' + str(counter))            

tableData = [['apples','oranges','cherries','banana'],
             ['Alice','Bob','Carol','David'],
             ['dogs','cats','moose','goose']]

printTable(tableData)
3
  • ... have you tried looking at the documentation for lists? Or any beginner tutorials on Python? Generally, you would use .append Commented May 30, 2018 at 2:53
  • Making a list and using .append should do it Commented May 30, 2018 at 3:01
  • Thank you juanpa.arrivillaga and mahir Commented May 30, 2018 at 5:00

1 Answer 1

1

Make a list, and then append the value of count to it every run of the loop.

def printTable(items):
    count_list = []
    for i in  range (len(items[0])):
        print ()
        counter = 0
        for j in range(len(items)):
            if len(items[i][j]) > counter:
            count = len(items[i][j])
            count_list.append(count)
            itemName = items[i][j]
        print ('the longest string is: ' + itemName + '; and its length is ' + str(counter))
    return count_list            

tableData = [['apples','oranges','cherries','banana'],
             ['Alice','Bob','Carol','David'],
             ['dogs','cats','moose','goose']]

printTable(tableData)
Sign up to request clarification or add additional context in comments.

2 Comments

I just realized the mistake i made with the 'count' and 'counter' mixing. Thank you Omegastick
Are you new to Python? There are quite a few style problems in the code. For example, we usually use snake_case for variable and function names. Variable names like count and counter are also easily confused (as you seem to have noticed). You also use a space after print, we don't usually use spaces between a function and it's parameters.

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.