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 functions

For instance, list(), len(), dict(), and set(), 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.

Categories:

Updated:

Comments