Sunday, December 24, 2023

Python Basics - Data Structures - Module 2

 In this module 2, we divide in three parts: Parts 1 (List and Tuples), part 2 (Dictionaries) and part 3 (Sets)


Image 1 - Pad Thai, fried noodle.

Parts 1 (List and Tuples)
Tuples is data type that built in Python to store multiple items in a single variable.
Tuples are similar to List, tey are immutable or their values can't be changed.

Tuples are an ordered sequence:
Ratings =(10,9,6,4,2)

Tuples:
String: 'disco'
int: 10
float: 1.2
tuple1 =('disco',10,1.2)
type(tuple1)=tuple

tuple1 =('disco',10,1.2)
index:       0        1    2
hence, tuple1[0]:'disco'
tupl1[1]:10

Index can be negative too:
tuple1 =('disco',10,1.2)
index:       -3      -2  -1
hence, tuple1[-3]:'disco'
tupl1[-1]:1.2

We can add tuples:
tuple1 =('disco',10,1.2)
tuple2 = tuple1 +("hard".10)
tuple2=('disco',10,1.2,"hard",10) 
index =     0       1   2       3      4

tuple2=('disco',10,1.2,"hard",10) 
index =     0       1   2      3       4
tuple2[0:3]: ('disco',10,1.2)
tuple2[3]: ('hard', 10)

len command:
len(('disco',10,1.2,"hard",10))= 5

Ratings =(10,9,6,5,10,8,9,6,2)
Ratings1=Ratings

Tuple: Nesting
nested_tuple= ((1, 20, (3, 4), (5, 6))
This nested_tuple contains 3 tuples, each with 2 elements.

We can access the elements of a nested_tuple by using indexing:
print(nested_tuple[1][0])
output: 3 ----> first element of second tuple

List is data type, can contain any data types include integers, strings and objects. Mutable, can be changed.
L=["Michael", 10.1, 1982]
index: 0            1        2
Hence, L[0]: "Michael"
L[1]: 10.1

Negative index:
L=["Michael", 10.1, 1982]
Index:  -3           -2    -1
L[-1]: 1982
L[-3]: "Michael"

List: slicing
L=["Michael", 10.1, 1982, "MJ", 1]
L[3:5]: ["MJ', 1]


Image 2 - Jambu bol, ilustrasi

Practice Quiz: Lists and Tuples

1) Consider the following tuple:
say_what=('say',' what', 'you', 'will')

What is the result of the following say_what[-1] ?
Answer: 'will'

2) Consider the following tuple A=(1,2,3,4,5)
what is the result of the following:A[1:4]:
answer: (2, 3, 4)
Note: A[1:4] is a slice of the list A that contains elements from index 1 to index 3. The first index is inclusive, while the second index is exclusive.

3) Consider the following tuple A=(1,2,3,4,5)
What is the result of the following: len(A)
answer: 5

4) Consider the following list B=[1,2,[3,'a'],[4,'b']]
What is the result of the following: B[3][1]
answer: b
Note:
B[3] returns the fourth element of the list B, which is [4, 'b'].
B[3][1] returns the second element of the list [4, 'b'], which is 'b'.
Therefore, the result of the expression B[3][1] is 'b'.

5)What is the result of the following operation?
[1,2,3]+[1,1,1]
Answer: [1, 2, 3, 1, 1, 1]
Note: The addition operator corresponds to concatenating a list.

6) What is the length of the list A = [1] after the following operation: A.append([2,3,4,5])
answer: 2
Note: The append() method in Python adds an element to the end of a list. In this case, the list A is initially [1]. After the operation A.append([2,3,4,5]), the new list A will be [1, [2, 3, 4, 5]]. Therefore, the length of the list A after the operation is 2.

7)What is the result of the following: "Hello Mike".split()
Answer: "Hello"," Mike"


Image 3 - Karya seni, Singapura

Part 2 : Dictionaries

List has index and elements

The Dictionary has key and value. 
- keys don't have to be integers. Key usually characters.
- key is immutable and unique
- Values similar to the elements in the List, contains information.

To create Dictionary, we use curly brackets:
{"key1":1, "key2":"2", "key3":[3,3,3], ('key4'):4}


Image 4 - Kemping untuk wisata

Practice Quiz: Dictionary

1) What are the keys of the following dictionary: {"a":1,"b":2}
answer: "a", "b"

2) Consider the following Python Dictionary: Dict={"A":1,"B":"2","C":[3,3,3],"D":(4,4,4),'E':5,'F':6} What is the result of the following operation: Dict["D"]
answer: (4, 4, 4)


 
Image 5 - Semak tidak terurus, ilustrasi

Part 3: Sets

Sets are type of collection means you can input different python types. You place the elements of a set within te curly brackets. 

You notice there are duplicates items.

example:
set1 = {"pop", "rock", "soul", "hard rock", "rock", "R&B", "rock", "disco"}

Convert List to Set:
album_list = [ "Michael Jackson", "Thriller", 1982, "00:42:19", \
              "Pop, Rock, R&B", 46.0, 65, "30-Nov-82", None, 10.0]

album_set = set(album_list) 

The set() function in Python is used to create a set object, which is an unordered collection of unique elements. In the given code snippet, album_list is a list containing 10 elements. When set(album_list) is called, it creates a new set object album_set containing only the unique elements of album_list. The resulting set object will contain the following elements:

{None, 'Pop, Rock, R&B', 1982, 10.0, 46.0, '30-Nov-82', 'Michael Jackson', '00:42:19', 'Thriller', 65}


Image 6 - Buah manggis, masih hijau

Practice Quiz Sets:
1) Consider the following set: {"A","A"}. What will the result be when the set is created?
answer: {"A"}
Note: A set can't have duplicate elements. Therefore the set will only one element which is "A".

2) What is the result of the following: type(set([1,2,3]))
answer: set
note: the result of type(set([1,2,3])) is <class 'set'>

3) What method do you use to add an element to a set?
answer: add
Note: my_set = set()
my_set.add(1)
my_set.add(2)
my_set.add(3)
print(my_set) # Output: {1, 2, 3}

4) What is the result of the following operation: {'a','b'} & {'a'}
answer: {'a'}
Note: The operation {‘a’,‘b’} & {‘a’} is the intersection of two sets. The intersection of two sets is the set of elements that are common to both sets. In this case, the intersection of {‘a’,‘b’} and {‘a’} is the set {‘a’}. Therefore, the result of the operation is {‘a’}.

JJ

No comments:

Post a Comment