Python Forum
First time poster...need help with a snippet
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
First time poster...need help with a snippet
#2
First mistake. You can't remove items while iterating through them.
Example. First thing you should notice it doesn't print them all.
def main():
    item_list = [
    'Heart of Gold', 'Rod of Ages', "Rabadon's Deathcap", 'Guardian Angel',
    'Bloodthirster', 'Ionic Spark', "Mejai's Soustealer"
    ]

    item_list2 = item_list[:] # shallow copy

    # Show error
    for i, item in enumerate(item_list):
        print(item)
        # remove every odd one
        if i % 2 == 1:
            item_list.remove(item)

    print()
    print(item_list)

    # build another list
    dump_list = []
    for i, item in enumerate(item_list2):
        if i % 2 == 1:
            dump_list.append(item)

    print()
    print(dump_list)
    for item in dump_list:
        item_list2.remove(item)

    print(item_list2)
main()
1. Use random.choice over random.randint(0, 1)
2. Use for loop and range over while. for counter in range(len(item_list)).

Only look at this. If you want to see how I would do it.
99 percent of computer problems exists between chair and keyboard.
Reply


Messages In This Thread
RE: First time poster...need help with a snippet - by Windspar - Jul-24-2019, 04:45 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020