Python Forum
Duplicated words in a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Duplicated words in a list
#7
Hi,

@pooyan89: iterating over an iterable with for x in range(...) and than using the index for accessing the item x of the iterable is a BIG anti-pattern. Simply don't do it. Python can directly iterate over iterables using for item ind iterable:. If you really need the index of item, use enumerate: for index, item in enumerate(iterable):

Except this, your code would only find duplicates if they follow each other like ['foo', 'bar', 'bar', 'spam'], but not ['bar', 'foo', 'spam', 'bar']. But the latter is requested in your homework.

Using the solution with set and the length comparison would be the way to do it, but if you need to use a loop, use a second list, the in-Operator and a comparison of the length:

>>> def has_duplicates(iterable):
...     other_list = []
...     for item in iterable:
...         if item not in other_list:
...             other_list.append(item)
...     if len(iterable) > len(other_list):
...         return True
...     else:
...         return False
... 
>>> foo = ['foo', 'bar' 'spam']
>>> bar = ['foo', 'bar', 'bar', 'spam']
>>> spam = ['bar', 'foo', 'spam', 'bar']
>>> has_duplicates(foo)
False
>>> has_duplicates(bar)
True
>>> has_duplicates(spam)
True
>>>
Regards, noisefloor
Reply


Messages In This Thread
Duplicated words in a list - by pooyan89 - Jun-15-2019, 12:47 PM
RE: Duplicated words in a list - by ThomasL - Jun-15-2019, 12:58 PM
RE: Duplicated words in a list - by pooyan89 - Jun-15-2019, 12:59 PM
RE: Duplicated words in a list - by ThomasL - Jun-15-2019, 01:03 PM
RE: Duplicated words in a list - by Yoriz - Jun-15-2019, 01:24 PM
RE: Duplicated words in a list - by pooyan89 - Jun-15-2019, 01:27 PM
RE: Duplicated words in a list - by noisefloor - Jun-15-2019, 06:18 PM
RE: Duplicated words in a list - by perfringo - Jun-15-2019, 08:21 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  capitalizing words in list Truman 1 3,535 Feb-19-2018, 11:40 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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