Instructor: Welcome back.
Let's do an exercise where we check
for duplicates in a list.
So I have some_list here,
and I want you to be able to check this list
and print whatever the duplicate values are.
In this case, we see that 'n' has duplicates
and also 'b' has duplicates.
So I want you to print 'b' and 'd' as a list in here.
How would you go about doing that?
Pause the video, give it a go,
otherwise, I'm gonna keep going with the answer.
And by the way, you're not allowed to use sets for this.
So for this exercise, you can't use the data structure sets.
Instead, you have to just use conditionals and loops
that we've learned in the past couple of videos.
So give it a try, pause the video, and when you're ready,
I'm gonna go ahead with the answer.
First, I'm going to create a variable called duplicates,
and this is going to be an empty list
that we're gonna populate with any duplicate values.
Next, I'm going to loop over this list,
so I'm going to say for value in some_list.
And in here, well, what can we do?
This is a tough one, but what I'm going to do
is say if some_list.count.
Remember, count allows us to count
how many times an item in a list exists.
And I'm going to say value so that some_list.count,
and I give it 'a', it's going to count for me
how many times 'a' happens in the list.
Very, very useful.
Again, if you didn't come up with that,
there's many solutions to this problem.
So there's no one right answer.
I'm just showing you how I would've done it.
Now here, I'm going to say if that's greater than 1.
In that case, that means there's a duplicate.
So I'm going to add it inside of the duplicates.
So let's just go ahead and say .append
because I wanna append, and in here say value.
And at the end of all this, let's just print duplicates.
Now, let's see if this works.
I'm going to click run, and, all right,
I get both 'b' and 'n', but I don't need this duplicates.
I just need to know what are the duplicates.
I just need one instance of 'b' and one instance of 'n'.
So what we can do here is do another if statement
and say if value is not in duplicates.
And, yes, this is a bit of a trick.
You may remember that not is the opposite, right.
So we're checking, "Hey, is value in duplicates?"
And not essentially says, "Hey, if value
is not in duplicates it reads like English."
And this is going to evaluate to true and false.
And then, finally,
make sure that we get the indentation right,
we're going to append the value.
So if I click run, I get 'b' and 'n'.
Again, if you didn't get this right away, don't worry.
It can get tricky, and this is one of those things
that you just need to keep practicing.
But you see here that I was able to use loops.
I was able to use logical operators, like not,
and conditionals, like if statements,
to solve a problem in just a few lines of code.