Written by: Elisardo

Edited by: Sooin

Week2 Introduction to Python & Data Science

Recap

Today we will learn

Answers


Variables

Before moving to todays lesson I will start by explaining the concept of variable in deeper detail.

So according to last session.

<aside> 💡 Variables

Variables are any letters, words, or combination of a letter with numbers to which you can store a value. You store a value with the assignment sign or a.k.a = I used the expression store by technically speaking is giving a name to the directory of your data stored in a memory. So, for example, the below code will store the value 3 in the memory. apple is the address that holds that value, so every time you use the variable apple, it will retrieve the number 3 stored in some place of the memory. You can verify the address by inputting the id() function.

apple = 3
print(apple)
id(apple)

</aside>

So, basically, this means that a variable is more like a “given name” to certain objects. This concept is important because when you replace a value from a variable x that is identical to the y, it will also replace the value of y. Let’s look at the example below

#create a variable `a` and create an identical variable `b`
a = [1,2,3]
b = a
#now replace the second value of the variable b by 10
b[1]=10
#check what happended to the variable a
a[1]
#This will return 10 since is identical to the variable b 

So to prevent this from happening you should copy the data a to b using one of the two methods [:] or .copy(). So if you execute the codes below you will see that a[1] = 10 does not affect other variables b and c .

a=[1,2,3]
b = a[:]
c = a.copy()
a[1] = 10
b
c

🐢 Last tip

You can also store more than 2 variable at once using the methods below

a, b = ('my', 'name')
(c, d) = 'is', 'elisardo'
a+" "+b+" "+c+" "+d

1. List data

Now let’s say you want to store a set of values at once (1,2,3,4,5,6,7,8,...).

One very effective way of doing it is using lists (list =[]). We use list a looooot like a looot in python since a list is

Within a list you can store any mix of data, that element or value inside the list is called item. Its default form is between brackets [] and separated with a comma ,.

# Numeric list
a = [1,2,3]
# String list
b = ["My", "name", "is"]
# Numeric + String List
c = [1,2,"Let's","go"]
# Numeric + List
d = [1,2, ["Hello", "World"]]

<aside> 📌 You can also create an empty list using list() Ex) a = list()

</aside>