The post Using while loop to move items between two lists in Python appeared first on We provide R, Python, Statistics Online-Learning Course.
]]>It is very often that items in list should be moved to another list in Python programming. For example, users trying to register on a website can only be moved to a verified user list after certain conditions are met. In such circumstance, a while loop can be applied.
#a list of new users waiting to verify
new_users = ['Wilson', 'Mico', 'Shirley', 'Dudu', 'Miaomiao','dudu']
#en empty list for verified user
verified_users = []
#while loop to verify every new user
#if the lower form of the new user is same as one of the user in
#verified user, then this user can not go into verified user list
while new_users:
new_user = new_users.pop()
if new_user.lower() not in verified_users:
verified_users.append(new_user.lower())
else:
print(new_user + " is already in the list")
#output
Dudu is already in the list
# Display all verified users.
print("\nThese are all the verified users now:")
for verify_user in verified_users:
print(verify_user)
#output
These are all the verified users now:
dudu
miaomiao
shirley
mico
wilson
The post Using while loop to move items between two lists in Python appeared first on We provide R, Python, Statistics Online-Learning Course.
]]>The post Using while loop to remove all specific elements from a list in Python appeared first on We provide R, Python, Statistics Online-Learning Course.
]]>Python provides function remove() to remove items in a list based on its value, but it removes only the first occurrence of instances if there are more than one such items existing in the list.
#creaate a list for car
cars = ["BMW","Mercedes","Toyota", "VOLVO","Lincoln", "Skoda","Toyota"]
#show the list
cars
#output
['BMW', 'Mercedes', 'Toyota', 'VOLVO', 'Lincoln', 'Skoda', 'Toyota']
#remove "Toyota" from list
cars.remove("Toyota")
#show car list again
cars
#output
['BMW', 'Mercedes', 'VOLVO', 'Lincoln', 'Skoda', 'Toyota']
From the code example above, we can see there is still a “Toyota” present in the list after we have used remove() function for the list. To address this issue, a while loop combined with conditional test for specific value inside the loop can be applied.
#create a list for cars
cars = ["BMW","Mercedes","Toyota", "VOLVO","Lincoln", "Skoda","Toyota"]
#show list
print(cars)
#output
['BMW', 'Mercedes', 'Toyota', 'VOLVO', 'Lincoln', 'Skoda', 'Toyota']
#using while loop, and remove "Toyota" using conditional test
while 'Toyota' in cars:
cars.remove('Toyota')
"show list again
print(cars)
#output
['BMW', 'Mercedes', 'VOLVO', 'Lincoln', 'Skoda']
The post Using while loop to remove all specific elements from a list in Python appeared first on We provide R, Python, Statistics Online-Learning Course.
]]>