Reputation: 3
I'm trying to create a code that will add milk to each list in a shopping cart (nested list). But if there is already milk in that list, milk should not be added to it.
shopping_cart= [
['Soap', 'Floss', 'Hand Sanitizer','Baby wipes'],
['Chickpeas', 'Blueberries', 'Granola'],
['Crayons','Construction paper','Printer ink']
]
if inputs== ('Calcium'):
for i in range(len(shopping_cart)):
shopping_list = shopping_cart[i]
for j in range(len(shopping_list)):
item=shopping_list[i][j]
if item!='milk':
item=item+'milk'
print ('Here is your new shopping cart:\n')
print (shopping_cart)
Upvotes: -1
Views: 190
Reputation: 29527
You'll probably also want to consider capitalization.
Should Milk be added if milk is there? If not, make sure you're comparing lowercase to lowercase.
new_item = "milk"
for l in shopping_cart:
l_lc = [x.lower() for x in l] # lowercase version of list
if new_item.lower() not in l_lc:
l.append(new_item)
You could also consider having a "shadow" dictionary so you're doing faster lookups and not converting the list to lowercase every time. Replace each list with a structure that has the list, as well as a dictionary of each item in lower case. May be overkill if it's a small list of lists.
Upvotes: 1
Reputation: 780798
You don't need nested loops. You just need to loop over the main list, not the nested lists, so you can append to that list. You can use the in
operator to test if a list contains something, you don't do that by looping (your loop will falsely say that the list doesn't contain milk
when any of the elements are not milk
).
Also, get in the habit of using for item in list:
rather than for index in range(len(list)):
for l in shopping_cart:
if 'milk' not in l:
l.append('milk')
Upvotes: 4