Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

module3_python

The document provides an overview of basic data structures in Python, including lists, tuples, sets, and dictionaries. It explains their characteristics, how to create and manipulate them, and highlights their differences, such as mutability and the requirement for dictionary keys to be immutable. The document also includes code examples to illustrate the usage of each data structure.

Uploaded by

ed.paesdev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

module3_python

The document provides an overview of basic data structures in Python, including lists, tuples, sets, and dictionaries. It explains their characteristics, how to create and manipulate them, and highlights their differences, such as mutability and the requirement for dictionary keys to be immutable. The document also includes code examples to illustrate the usage of each data structure.

Uploaded by

ed.paesdev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

27/12/2024, 16:38 module3_python

Unit 3: Basic Data Structures

Learning Objective:

1. Recognize the key characteristics of each structure. Correctly utilize each structure when appropriate
and access the corresponding data stored on the structure.

Refer to this Doc (https://docs.python.org/3/tutorial/datastructures.html) for additional information on each


data structure.

3.1: List

List: a mutable data structure that stores elements in an unordered format, like an array.

In [ ]: # Initiate an empty list


list1 = []
# OR
list1 = list()

# Initiate a list with elements


list2 = ['hello', 'hola', 'olá']

"""
Elements in list does NOT have to be the same type, but this is uncommon.
In this case, each list could represent the series of information about a p
erson,
but you will need to remember what information is stored at each index. ---
> There is a better option for this purpose - dictionary.
"""
list3 = ["John", "male", 20, False]

In [ ]: # Accessing information stored in the list by position ("index")


# Note: in CS, first position is ALWAYS 0
print("First element in list2 : "+ list2[0])
print("Second element in list2 : "+ list2[1])

First element in list2 : hello


Second element in list2 : hola

In [ ]: # Insert a new element as a specific location, at index 1


list2.insert(1,'hallo')
list2[1]

Out[ ]: 'hallo'

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 1/10
27/12/2024, 16:38 module3_python

In [ ]: # Append a new element at the END of the list


list2.append('bye')
list2

Out[ ]: ['hello', 'hallo', 'hola', 'olá', 'bye']

In [ ]: # Remove an element from the list by specifying the element that you want t
o remove
list2.remove('hello')

In [ ]: # list2 after 'hello' is REMOVED


list2

Out[ ]: ['hallo', 'hola', 'olá', 'bye']

In [ ]: """
Another way to remove an element: pop()
pop() allows you to identify the position you
"""

list2.append("hello")

list2.pop()

list2

Out[ ]: ['hallo', 'hola', 'olá', 'bye']

In [ ]: """
Lists could also be sorted.
Method of sorting depends on how the comparable interface is implemented fo
r the objects in the list.

In this case of list2, sort() works by sorting individual characters in the


string according to the ASCII code.
"""
list2.sort()
list2

Out[ ]: ['bye', 'hallo', 'hola', 'olá']

In [ ]: """
Since list is dynamic, meaning that the size of the list grow or shrink as
we insert or remove elements,
we could call len() to find the size of the list at a given time.
"""

# Since len() returns an int, in order to concatenate it to a string, we ne


ed to cast it.
print("size of list1 = " + str(len(list1)))
print("size of list2 = " + str(len(list2)))

size of list1 = 0
size of list2 = 4

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 2/10
27/12/2024, 16:38 module3_python

In [ ]: # Print items in list as a string, separated by a comma


",".join(list2)

Out[ ]: 'bye,hallo,hola,olá'

In [ ]: # You could also have a list of lists. For example:

lists = []
lists.append([1,2,3])
lists.append(['a','b','c'])

lists

Out[ ]: [[1, 2, 3], ['a', 'b', 'c']]

In [ ]: # Similarly, you could index the over multi-dimensional lists

lists[1]

Out[ ]: ['a', 'b', 'c']

In [ ]: lists[1][0]

Out[ ]: 'a'

3.2: Tuple

Tuple: immutable "list" which cannot be manipulated once created.

They support all the operations lists supports, except for those that modify the list.

In [ ]: # Initialize an empty tuple


y = tuple()
y

# Create a new tuple of elements


x = (1,2,3)

In [ ]: # ERROR: canot add to a tuple


x.append(4)

--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
<ipython-input-30-89cbd0c10841> in <module>()
1 # ERROR: canot add to a tuple
----> 2 x.append(4)

AttributeError: 'tuple' object has no attribute 'append'

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 3/10
27/12/2024, 16:38 module3_python

In [ ]: # This is OK because creating a new tuple with x and (4,5,6) added at the e
nd
x + (4,5,6)

Out[ ]: (1, 2, 3, 4, 5, 6)

In [ ]: # x is NOT modified by the previous line


x

Out[ ]: (1, 2, 3)

In [ ]: # Create a new tuple with x apearing twice


x * 2

Out[ ]: (1, 2, 3, 1, 2, 3)

In [ ]: # Index on the elements in the tuple


x.index(3)

Out[ ]: 2

In [ ]: # shorthand for
# (a,b,c) = (1,2,3)

# This also assigns a = 1, b = 2, c = 3

a,b,c = 1,2,3

In [ ]: a

Out[ ]: 1

In [ ]: b

Out[ ]: 2

In [ ]: c

Out[ ]: 3

In [ ]: # Convert a tuple into a list


x = (1,2,3,4)
list(x)

Out[ ]: [1, 2, 3, 4]

In [ ]: # Convert a list into a tuple


x = [1,2,3,4]
tuple(x)

Out[ ]: (1, 2, 3, 4)

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 4/10
27/12/2024, 16:38 module3_python

In [ ]: # Declare a new tuple, name "person"


person = ('Jane','Doe', 21)

# "Pack"/associate each element of the tuple with a label. Note the order o
f labels.
first, last, age = person

In [ ]: first

Out[ ]: 'Jane'

In [ ]: last

Out[ ]: 'Doe'

In [ ]: age

Out[ ]: 21

In [ ]: # ERROR: x is a tuple is 4 values but ONLY trying to unpack 3 elements.


# Mismatch on the size of tuple
x = (1,2,3,4)

a,b,c = x

--------------------------------------------------------------------------
-
ValueError Traceback (most recent call las
t)
<ipython-input-45-4acb77e9e93d> in <module>()
3 x = (1,2,3,4)
4
----> 5 a,b,c = x

ValueError: too many values to unpack (expected 3)

In [ ]: # This is OK!
x = [1,2,3,4]
a,b,c,d = x

In [ ]: a

Out[ ]: 1

In [ ]: b

Out[ ]: 2

In [ ]: c

Out[ ]: 3

In [ ]: d

Out[ ]: 4

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 5/10
27/12/2024, 16:38 module3_python

3.3: Set

Set: a mutable data structure that stores non-duplicated, immutable objects and sorts the elements in
ascending order. Every element in the set is unique.

In [ ]: # Initialize an empty set


newSet = set()
newSet

Out[ ]: set()

In [ ]: # A set with elements


ex1 = {1, 2, 2, 1, 1}

ex1

Out[ ]: {1, 2}

In [ ]: ex2 = {j for j in range(10)}


ex2

Out[ ]: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

In [ ]: # 2 already exists in the ex2. What happen if we want to add 2 again?


# Note: The implementation for set did NOT define append(), so we will us
e add().
# add() will insert the new element in the correct position with the so
rting of the set
ex2.add(2)
ex2.add(100)
ex2.add(50)
ex2

Out[ ]: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 50, 100}

In [ ]: # mutable objects can't go in a set


d_set = {[1,2,3]}

d_set

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
<ipython-input-55-6b6994b2706f> in <module>()
1 # mutable objects can't go in a set
----> 2 d_set = {[1,2,3]}
3
4 d_set

TypeError: unhashable type: 'list'

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 6/10
27/12/2024, 16:38 module3_python

In [ ]: # Convert a list to a set


ages = [10, 5, 4, 5, 2, 1, 5]

set_of_ages = set(ages)

set_of_ages

Out[ ]: {1, 2, 4, 5, 10}

In [ ]: # Convert a set to a list


list_of_ages = list(set_of_ages)

list_of_ages

Out[ ]: [1, 2, 4, 5, 10]

In [ ]: # Convert a set to a tuple


tuple_of_ages = tuple(list_of_ages)

tuple_of_ages

Out[ ]: (1, 2, 4, 5, 10)

In [ ]: # Order is irrelevant in set comparison since elements are sorted

{1,2,3} == {2,1,3}

Out[ ]: True

3.4: Dictionary

Dictionary: a data structure that stores key-value pairs in which the keys MUST be immutatble objects.

In [ ]: # Initiate an empty dictionary


# Same as set, but with :
dict = {}

# Declare a dictionary with key/value pairs


dict2 = {'a': 5, 'b': 10, 'c': 100, 'd': 9.5}

In [ ]: # Accessing data in a dictionary with a key


dict2['b']

Out[ ]: 10

In [ ]: # Update value of an existing key


dict2['b'] = 50

dict2['b']

Out[ ]: 50

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 7/10
27/12/2024, 16:38 module3_python

In [ ]: # What happen if we want to access the value for a non-existing key? (e.g.
'z')

# We might expect an ERROR because this key doesn't exist, so it doesn't ha


ve a value.
# That is a correct assumption.
dict2['z']

--------------------------------------------------------------------------
-
KeyError Traceback (most recent call las
t)
<ipython-input-63-ddfe9c24c2d2> in <module>()
4 # We might expect an ERROR because this key doesn't exist, so it d
oesn't have a value.
5 # That is a correct assumption.
----> 6 dict2['z']

KeyError: 'z'

In [ ]: # But if what if we do this, will this still return an ERROR?


dict2['z'] = 999

dict2['z']

Out[ ]: 999

WHY??

The previous block of code works because we "update" the value of the key first, update = insert (in this
case), and by the time we want to access the value of this key, this key already exists in the dictionary for the
assigned mapping.

In [ ]: # Values in the dictionary can be mix-typed


# Let's look at an example with dict{}, an empty dictionary initiated abov
e.
# Fist, we will insert some key/value pairs into the program.

dict["greeting"] = "hello message"


dict["alphabet"] = ['a', 'b', 'c', 'd', 'e']
dict["check-in"] = False
dict["phoneNumber"] = 8007782346

dict

Out[ ]: {'alphabet': ['a', 'b', 'c', 'd', 'e'],


'check-in': False,
'greeting': 'hello message',
'phoneNumber': 8007782346}

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 8/10
27/12/2024, 16:38 module3_python

In [ ]: # IMPORTANT Note: key must be immutatble objects (something that cannot be


changed)
# String is immutable, because you could not just delete a character in a s
tring. A string is a string, the way it is.

# From above, we see that a list can be a value in the dictionary.


# What happen when we try to make it a key?

# ERROR: unhashable type of list

# Because we could modify the list by inserting new element, sorting elemen
ts, deleting elements, or other ways of modifying it, it CANNOT be a key

dict[['a','b', 'c']] = [False, True, False]

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
<ipython-input-66-7e50947ec831> in <module>()
9 # Because we could modify the list by inserting new element, sorti
ng elements, deleting elements, or other ways of modifying it, it CANNOT b
e a key
10
---> 11 dict[['a','b', 'c']] = [False, True, False]

TypeError: unhashable type: 'list'

In [ ]: # But since tuple is immutatble, we could replace the list with a tuple
dict[('a','b', 'c')] = [False, True, False]

dict

Out[ ]: {('a', 'b', 'c'): [False, True, False],


'alphabet': ['a', 'b', 'c', 'd', 'e'],
'check-in': False,
'greeting': 'hello message',
'phoneNumber': 8007782346}

In [ ]: # We could also retrieve all the keys


dict.keys()

Out[ ]: dict_keys(['greeting', 'alphabet', 'check-in', 'phoneNumber', ('a', 'b',


'c')])

In [ ]: # Or all values
dict.values()

Out[ ]: dict_values(['hello message', ['a', 'b', 'c', 'd', 'e'], False, 800778234
6, [False, True, False]])

In [ ]: # Elements in a dictionary could also be returned as a pair.


dict.items()

Out[ ]: dict_items([('greeting', 'hello message'), ('alphabet', ['a', 'b', 'c',


'd', 'e']), ('check-in', False), ('phoneNumber', 8007782346), (('a', 'b',
'c'), [False, True, False])])

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 9/10
27/12/2024, 16:38 module3_python

In [ ]:

https://cdn.evg.gov.br/cursos/338_EVG/htmls/modulo03_html01.html 10/10

You might also like