Python Forum
finding similar objects in a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
finding similar objects in a list
#1
I am new to python and programming in general.I wanted to write a code which prints the similar elements from 2 lists .For example if a=[1,2,3,4,5] and b=[0,2,4,6] , I would want a c=[2,4]. Here is what I did:

def simi(a,b):
    a,b,c=[],[],[]
    for i in a:
        for j in b:
            if i==j:
                c.append(i)
            else:
                continue
    return (c)
[python]
Reply
#2
check your line#2
Do you really want to overwrite the user supplied arguments a and b with empty lists? :-)

Note that your code is not pythonic and there are better ways to do the same, without using nested loops. check using set
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(Jun-22-2018, 06:57 AM)DRPR Wrote: I am new to python and programming in general.I wanted to write a code which prints the similar elements from 2 lists .For example if a=[1,2,3,4,5] and b=[0,2,4,6] , I would want a c=[2,4]. Here is what I did:

def simi(a,b):
    a,b,c=[],[],[]
    for i in a:
        for j in b:
            if i==j:
                c.append(i)
            else:
                continue
    return (c)
  • In your function, you overwrite a and b, you have to initialize only c
  • If you find an equal element - you can stop the search
               if i==j:
                   c.append(i)
                   break
  • You don't need else for an empty action - if may exist without else. You only use continue if you have more code in the loop that you want to bypass - and even then it is not advised (unless you want to avoid indenting large block of code)
  • It is more efficient to check the presence of an element in a list with an operator in
  • One-letter names are bad practice (with very few exceptions). Variable names are a part of the code documentation, and should tell the code reader their purpose. It is advisable to acquire the habit of naming your variables properly early in the study process

So this is how your function should look like
def similar_elements(list1, list2):
    similars = []
    for elem in list1:
        if elem in list2:
            similars.append(elem)
    return similars
Of course, experienced Pythonista would write it at least as
[elem for elem in list1 if elem in list2]
and there are couple of other ways to write it - but that will come in the future.

Good luck with your studies!
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#4
(Jun-22-2018, 07:29 AM)volcano63 Wrote: [quote='DRPR' pid='50443' dateline='1529650625'] I am new to python and programming in general.I wanted to write a code which prints the similar elements from 2 lists .For example if a=[1,2,3,4,5] and b=[0,2,4,6] , I would want a c=[2,4]. Of course, experienced Pythonista would write it at least as
[elem for elem in list1 if elem in list2]
and there are couple of other ways to write it - but that will come in the future. Good luck with your studies!

I did the method for the experienced pythonista! but it returned a an error:
def simi1(list1,list2):
    c=[]
    [elem for elem in list1 if elem in list2]
    c.append(elem)
    return(c)
Error:
NameError: name 'elem' is not defined
Any tips?
Reply
#5
(Jun-22-2018, 09:55 AM)DRPR Wrote: I did the method for the experienced pythonista! but it returned a an error:
def simi1(list1,list2):
    c=[]
    [elem for elem in list1 if elem in list2]
    c.append(elem)
    return(c)
Error:
NameError: name 'elem' is not defined
Any tips?

I probably should not have shown it Blush (if I hadn't, someone had probably "corrected" me Naughty ). I have committed a sin I often berate others for - showing an advanced technique to a newbie without a disclaimer.

This is the proper code
def simi1(list1,list2):
    return [elem for elem in list1 if elem in list2]
or - by set, as buran suggested
def simi1(list1,list2):
    return set(list1).intersection(list2)
The problem with those 2 solutions for you - jumping stages. Mastering loops is a step to mastering list comprehension.
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Error is finding mean of a list PythonBoy 4 843 Sep-11-2023, 02:38 PM
Last Post: PythonBoy
  Finding combinations of list of items (30 or so) LynnS 1 836 Jan-25-2023, 02:57 PM
Last Post: deanhystad
  Creating list of lists, with objects from lists sgrinderud 7 1,561 Oct-01-2022, 07:15 PM
Last Post: Skaperen
Question Keyword to build list from list of objects? pfdjhfuys 3 1,499 Aug-06-2022, 11:39 PM
Last Post: Pedroski55
Question Finding string in list item jesse68 8 1,798 Jun-30-2022, 08:27 AM
Last Post: Gribouillis
  How to store the resulting Doc objects into a list named A xinyulon 1 1,851 Mar-08-2022, 11:49 PM
Last Post: bowlofred
  Grouping and sum of a list of objects Otbredbaron 1 3,129 Oct-23-2021, 01:42 PM
Last Post: Gribouillis
  Sum similar items tester_V 3 1,898 Jun-29-2021, 06:58 AM
Last Post: tester_V
  Passing List of Objects in Command Line Python usman 7 3,084 Sep-27-2020, 03:45 PM
Last Post: ndc85430
  How to create and define in one line a 2D list of class objects in Python T2ioTD 1 1,986 Aug-14-2020, 12:37 PM
Last Post: Yoriz

Forum Jump:

User Panel Messages

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