Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Removing duplicate Image
#4
A list comprehension is a neat way to combine for-loops with lists (or many other iterable structures). You can generate a new list out of an old list (even with conditions) by iterating through each element of the old list all in one line. For example:
Lets say we have the list numbers = [1, 2, 3, 4, 5, 7, 9] and we want to only keep the odd numbers. Without list comprehension we would do this:
numbers = [1, 2, 3, 4, 5, 7, 9]
odds = []
for n in numbers:
    if n % 2 == 1:
        odds.append(n)
Which would modify the list odds so that it would look like this: odds = [1, 3, 5, 7, 9]
Now with list comprehensions it would look like this:
numbers = [1, 2, 3, 4, 5, 7, 9]
odds = [n for n in numbers if n % 2 == 1]
As you can see we squashed the complete for-loop together with the initialization of the odds list in one line. Of course depending of the use case the if-cause would be optional, but in this case and your presented problem you would need it. There are even some more tricks that can be done with list comprehensions, but this is all you need for now.
So list comprehensions help you to filter your data using one line of code and in a nice readable way.
Here is a nice tutorial on how to use list comprehensions: https://realpython.com/list-comprehension-python/
Reply


Messages In This Thread
Removing duplicate Image - by Evil_Patrick - Jan-23-2020, 02:19 PM
RE: Removing duplicate Image - by ThiefOfTime - Jan-23-2020, 02:34 PM
RE: Removing duplicate Image - by Evil_Patrick - Jan-23-2020, 02:47 PM
RE: Removing duplicate Image - by ThiefOfTime - Jan-23-2020, 05:25 PM
RE: Removing duplicate Image - by benlyboy - Jan-23-2020, 09:19 PM
RE: Removing duplicate Image - by ThiefOfTime - Jan-23-2020, 09:29 PM
RE: Removing duplicate Image - by benlyboy - Jan-23-2020, 09:37 PM
RE: Removing duplicate Image - by snippsat - Jan-24-2020, 12:28 PM
RE: Removing duplicate Image - by Evil_Patrick - Jan-26-2020, 03:48 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Removing duplicate list items eglaud 4 2,734 Nov-22-2019, 08:07 PM
Last Post: ichabod801
  removing duplicate numbers from a list calonia 12 5,370 Jun-16-2019, 12:09 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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