On 26/10/14 22:15, Caroline H wrote:
For example,
lst1 = [2,5,6,7,2]
lst2 = [2,4]
it comes up with new_list = [2] when I need it to come up with new_list
= [2,2]
Check the logic in the if statement. Walk through it and se if it does
what you expect. You are basically doing the right thing, except...
The code I have so far is:
new_list = []
i = 0
j = 0
if len(lst1)<=len(lst2):
for i in range(len(lst1)):
if lst1[i] in lst2:
new_list.append(lst1[i])
else:
for j in range(len(lst2)):
if lst2[j] in lst1:
new_list.append(lst2[j])
Rather than using indexing you should use the 'for' loop directly
on the lists:
for item in list
if item in otherlist:
newlist.append(item)
Its much easier to read and leaves Python to do all the index management
for you.
Its rare to need to use indexes in conjunction with a
'for' loop.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor