Home > Blockchain >  Python 'for item in list' not changing list items
Python 'for item in list' not changing list items

Time:09-17

board = ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']
for item in board:
    if item == 'b':
        item = 'a'
print(board)

The result of this block of code is that none of the list items turn to 'a'. I cant seem to figure out why that is. I can still do a for loop where I use an index value to change each item in the list like such.

board = ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']
for i in range(0, len(board)):
    if board[i] == 'b':
        board[i] = 'a'
print(board)

I don't understand why the first solution dosent work

CodePudding user response:

item is a variable. for item in board: keeps assigning values from board to item as the loop progresses. item holds a reference to a value in board but it has no idea that board exists or holds the value too. You could track the position in board with enumerate and assign as needed

board = ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']
for i, item in enumerate(board):
    if item == 'b':
        board[i] = 'a'
print(board)

Or you could use a list comprehension to create a new board

board = ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']
newboard = [value if value != 'b' else 'a' for value in board]

Or assign that new list back to the original board variable

board = ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']
board = [value if value != 'b' else 'a' for value in board]

Or refill the original list with the new values

board = ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']
board[:] = [value if value != 'b' else 'a' for value in board]

CodePudding user response:

You need a small change in your code. You need to access the items in your list in sequence and see if, at a particular location, there exists the letter 'b'.

board = ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']
for item in range(len(board)):
    if board[item] == 'b':
        board[item] = 'a'
print(board)

Hopefully, this helps.

  • Related