Python 07
Python Sets
Another intersting data type is set
. A set
is an unordered collection data type.
list1 = ['ruby', 'python', 'javascript', 'Go']
list2 = ['ruby', 'SQL', 'javascript', 'JAVA']
There are two lists above. How do we join this two lists together and remove duplicates? That is the turn for set
.
β In this examples list name is
list1
but avoid using keyword that has same name with functionsFor instance,
list()
,len()
,dict()
, andset()
, etcβ¦
First add two lists together programming languages = list1 + list2
. Then use print()
to see the result.
# result
['ruby', 'python', 'javascript', 'Go', 'ruby', 'SQL', 'javascript', 'JAVA']
Second, we need to get rid of duplicates. Wrap the list1 + list2
in set()
function.
list1 = ['ruby', 'python', 'javascript', 'Go']
list2 = ['ruby', 'SQL', 'javascript', 'JAVA']
programming_lang = set(list1 + list2)
print(programming_lang)
print(type(programming_lang))
# result
{'Go', 'javascript', 'SQL', 'python', 'JAVA', 'ruby'}
<class 'set'>
You can see it returns the data type set
. It is not a list
, so we cannot use indexing here. This means data type set
is not subscriptable.
print({1, 2, 2, 2}) # returns {1, 2}
print({1, 2, 2, 3, 3}[0]) # β
Set excersice
Letβs practice set
Create a function unique
, that takes in a list
and returns only unique items.
'''
create a function unique, that takes in a list of languages and returns only unique items
>>> unique(['ruby', 'ruby', 'python'])
['ruby', 'python']
'''
Toggle Answer π
# result will vary
ex_1 = ['ruby', 'ruby', 'python']
ex_2 = ['ruby', 'python', 'Go', 'JAVA', 'Go', 'ruby']
def unique(languages):
return list(set(languages))
print(unique(ex_1))
print(unique(ex_2))
Bonus! Can we put the code in one line as it is short code?
If you want to put unique in one line, we could do
def unique(languages): return list(set(languages))
or we can use
lambda
To use
lambda :
unique = lambda languages : list(set(languages))
It is an overkill for this function, but still it is good to practice lambda here to get familiar with it.
Python Loops
Letβs move on to most commonly used feature in programming: Loops
fruits = ['π', 'π', 'π', 'π', 'π', 'πͺ']
Here is our fruits list again from the previous post. Now we want to get all the items in list, and we know that we can get the items with index.
fruits = ['π', 'π', 'π', 'π', 'π', 'πͺ']
print("fruit:", fruits[0], 0)
print("fruit:", fruits[1], 1)
print("fruit:", fruits[2], 2)
print("fruit:", fruits[3], 3)
Try this code from your terminal. We got fruit, and idex of the fruit from the code above.
# result
fruit: π 0
fruit: π 1
fruit: π 2
fruit: π 3
But this is not efficient enough. Imagine you are dealing with Amazon item lists or Netflix movie lists. We canβt manually type every single time. And thankfully, we have a loop
to figure this out.
For loop
We can loop through the items of the list with for loop
. The basic structure will be like this:
for placeholder in list:
# do something here(indented)
The placeholder can be anything, and usually it is a singular term of list. For example, fruit in fruits
, fruit
is the item and fruits
is the list.
for fruit in fruits:
print("fruit:", fruit)
# result
fruit: π
fruit: π
fruit: π
fruit: π
This simple line of code saves you so much time! Now we donβt have to manually type when we want to get the items.
But we are missing index
, so letβs get an index
enumerate
There is another helpful function called enumerate()
which returns a list of items with the indices.
Try run this code
fruits = ['π', 'π', 'π', 'π', 'π', 'πͺ']
# added list() to see the result
print(list(enumerate(fruits)))
# result
[(0, 'π'), (1, 'π'), (2, 'π'), (3, 'π'), (4, 'π'), (5, 'πͺ')]
The function enumerate
returns a tuple
with the according indicies.
Unpacking tuple
Now we got the tuples, it is time for unpacking. Remeber from the previous post, variables
can be assigned in this way
name, age = "your_name", 20
We can apply this rule to tuple as well. First we need to have a tuple
, and then assign the values in different variables
.
my_tuple = (0, 'π')
index, fruit = (0, 'π')
print(index)
print(fruit)
# result
0 # index
π # fruit
For loop indexing
We have a unpacked tuple
and the enumerate()
function. To combine these two, we need to do the following:
fruits = ['π', 'π', 'π', 'π', 'π', 'πͺ']
for index, fruit in enumerate(fruits):
print("fruit:", fruit, index)
# result
fruit: π 0
fruit: π 1
fruit: π 2
fruit: π 3
fruit: π 4
fruit: πͺ 5
We set the placeholder as variable
index and fruit, and enumerate
the array to get the list [(0, 'π'), (1, 'π'), (2, 'π'), (3, 'π'), (4, 'π'), (5, 'πͺ')]
Each time when for loop triggers print()
, first item of tuple will be index(0, 1, 2, ...)
and the second item of the tuple will be the fruit
.
apply for loop
We can use the for loop in many different situations. One example, if we ordered five kiwis, and want to add five kiwis in the list.
fruits.append('π₯')
fruits.append('π₯')
fruits.append('π₯')
fruits.append('π₯')
fruits.append('π₯')
That is one way to achieve the goal, but it is not DRY(Donβt repeat yourself) code. So, we can use for loop in this scenario.
fruits = ['π', 'π', 'π', 'π', 'π', 'πͺ']
for _ in range(5):
fruits.append('π₯')
print(fruits)
# result
['π', 'π', 'π', 'π', 'π', 'πͺ', 'π₯', 'π₯', 'π₯', 'π₯', 'π₯']
βReminderβ The function
range()
returns a sequence of numbers starting from 0 by default.
While loop
In previous post, we studied while
statement with the number guessing game. So in this section, we are skim through it.
# Watch out for infinite loop
Sam = 'sitting'
# != means not equals to
while Sam != 'standing':
print('Stand UP!!!') # infinite loop.
counter = 0
while counter < 10:
print(counter)
counter += 1
Although we used it for the number guessing game, in general, while loop
is not used as much as for loop
.
As we are the beginners, using for loop
would be a good choice to practice.
Comments