Callum Houghton
Callum Houghton

Reputation: 25

Iterate over a list in a class

I'm trying to iterate through a list in a class, but instead only the first member of the list is being printed out to the console. How do print each element?

class CodeManager(object):
    """Separates the input string into individual characters in a list"""

    characters = []

    def __init__(self, stringCode):
        self.stringCode = stringCode

    def LoopThroughList(self):

        self.characters = list(self.stringCode.upper())
        for chars in self.characters:
            return chars

And then I create a class object in my main Python file:

code = CodeManager.CodeManager("Hello my name is Callum")
print (code.LoopThroughList())

Upvotes: 1

Views: 134

Answers (5)

Tutorial Doctor
Tutorial Doctor

Reputation: 1

Yeah. List comprehension works with a slight modification:

class CodeManager(object):
"""Separates the input string into individual characters in a list"""

    characters = []

    def __init__(self, stringCode):
        self.stringCode = stringCode
        self.characters = stringCode.upper()

    def LoopThroughList(self):
        return [chars for chars in self.stringCode.upper().split()]


code = CodeManager("Hello my name is Callum")
print (code.LoopThroughList())

['HELLO','MY','NAME','IS','CALUM']

Or if you want this:

class CodeManager(object):

characters = []

def __init__(self, stringCode):
    self.stringCode = stringCode
    self.characters = stringCode.upper()

def LoopThroughList(self):
    return [chars for chars in self.stringCode.upper()]


code = CodeManager("Hello my name is Callum")
print (code.LoopThroughList())

['H', 'E', 'L', 'L', 'O', ' ', 'M', 'Y', ' ', 'N', 'A', 'M', 'E', ' ', 'I', 'S', ' ', 'C', 'A', 'L', 'L', 'U', 'M']

your characters variable is a class variable, not an instance variable (there is a difference).

Upvotes: -1

Padraic Cunningham
Padraic Cunningham

Reputation: 180522

You are returning after the first iteration:

for chars in self.characters:
        return chars # ends loop

If you want to see all the characters, use print or yield and iterate over code.LoopThroughList()

for chars in self.characters:
        print(chars)

Or yield and make the method a generator:

 for chars in self.characters:
        yield chars

Then:

for ch in code.LoopThroughList():
    print(ch)

Using yield will actually allow you to use each character returned which is probably closer to what you are trying to do in your own code.

If you just want to see each char outputted on a new line, you can use str.join:

self.characters = list(self.stringCode.upper())
        return "\n".join(self.characters)

You also don't need to call list on self.stringCode.upper(), you can iterate directly over a string.

Upvotes: 2

Joseph Stover
Joseph Stover

Reputation: 427

You can use list comprehension

def LoopThroughList(self):
    return [chars for chars in self.stringCode.upper()]

This will return a list of all the characters in the stringCode variable

Upvotes: 0

taesu
taesu

Reputation: 4580

you're returning , hence first element in the list.

class CodeManager(object):
    """Separates the input string into individual characters in a list"""

    characters = []

    def __init__(self, stringCode):
        self.stringCode = stringCode

    def LoopThroughList(self):
        self.characters = list(self.stringCode.upper())
        for chars in self.characters:
            print chars

code = CodeManager("Hello my name is Callum")
code.LoopThroughList()

Upvotes: 0

Bakuriu
Bakuriu

Reputation: 102039

Your loop is returning the first character. A return statement will block the execution of the remaining iterations of the loop.

You probably wanted to use print instead of return:

def loop_through_list(self):
    self.characters = list(self.stringCode.upper())
    for char in self.characters:
        print(char)

Used as:

code = CodeManager.CodeManager("Hello my name is Callum")
code.loop_through_list()

Moreover, your definition of characters = [] in the class is pretty useless. You are shadowing the class attribute inside the method call.

Upvotes: 1

Related Questions