Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
manipulating two lists
#4
The quick way is to change new_accounts into a set instead of a list; sets store unique values only.

existing_accounts = ["Marcis", "John", "Tim"]
new_accounts = ["Sarah", "Marcis", "Tim", "Marcis"]

for new_account in  set(new_accounts):
    if new_account in existing_accounts:
        print(new_account + " is already taken!")
        new_accounts.remove(new_account)
    else:
        print (new_account + " you are now registered.")
        existing_accounts.append(new_account)
        new_accounts.remove(new_account)
             
print(existing_accounts)
print(new_accounts)
Something to be aware of when iterating over lists: alterations to the list inside the loop can cause problems. For instance, if Tim did not have an existing account, he would likely not be listed in new_accounts at the end. This is due to the indices of the contents changing because of the removal of Marcis, but the index for the loop doesn't adjust accordingly. Remove Tim from existing_accounts and run it again; you should find a problem.
Reply


Messages In This Thread
manipulating two lists - by rancans - Apr-15-2020, 08:33 PM
RE: manipulating two lists - by bowlofred - Apr-15-2020, 08:42 PM
RE: manipulating two lists - by rancans - Apr-15-2020, 09:36 PM
RE: manipulating two lists - by stullis - Apr-15-2020, 09:51 PM
RE: manipulating two lists - by rancans - Apr-16-2020, 04:15 PM
RE: manipulating two lists - by bowlofred - Apr-15-2020, 09:54 PM
RE: manipulating two lists - by deanhystad - Apr-15-2020, 09:55 PM
RE: manipulating two lists - by stullis - Apr-15-2020, 09:58 PM
RE: manipulating two lists - by deanhystad - Apr-16-2020, 06:00 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,524 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  Manipulating data from a CSV EvanS1 5 2,806 Jun-12-2020, 05:59 PM
Last Post: perfringo
  Manipulating index value, what is wrong with this code? Emun 1 1,838 Feb-05-2020, 07:18 AM
Last Post: perfringo
  Manipulating the filename of an output script mckinneycm 4 12,012 Jan-15-2020, 07:29 PM
Last Post: mckinneycm
  Manipulating Excel with Python. Spacely 2 3,750 Jun-25-2019, 01:57 AM
Last Post: Dequanharrison
  Manipulating CSV Prince_Bhatia 1 2,000 Apr-25-2019, 11:55 AM
Last Post: Gribouillis
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,408 Mar-20-2019, 08:01 PM
Last Post: stillsen
  Reading and manipulating csv Prince_Bhatia 11 5,247 Mar-14-2019, 11:40 AM
Last Post: Larz60+
  Manipulating an Excel Workbook Stanimal 4 3,076 Jan-18-2019, 11:03 PM
Last Post: Stanimal
  Manipulating Binary Data arsenal88 10 8,841 Apr-25-2017, 02:30 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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