0% found this document useful (0 votes)
0 views19 pages

Chapter 2. Variables and Basic Data Structures

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views19 pages

Chapter 2. Variables and Basic Data Structures

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Chapter 2.

Variables and
Basic Data Structures
Outline
1. Variables
2. Data Structure

2.1 Data Structure - Strings

2.2 Data Structure - Lists

2.3 Data Structure - Tuples

2.4 Data Structure - Sets

2.5 Data Structure - Dictionaries

2
1.Variables
A variable is a string of characters and numbers associated with a piece of information.

The assignment operator, denoted by the “=” symbol, is the operator that is used to
assign values to variables in Python.

The line x=1 takes the known value, 1, and assigns that value to the variable with name
“x”. After executing this line, this number will be stored into this variable. Until the value is
changed or the variable deleted, the character x behaves like the value 1.
2. Data Structure

Python data types chart


2.1 Data Structure - Strings

A string is a sequence of characters, such as “Hello World” we saw


in chapter 1. Strings are surrounded by either single or double
quotation marks.
Example: Print “I love Python!” to the screen.
Assign the character “S” to the variable with name s. Assign the
string “Hello World” to the variable w. Verify that s and w have the
type string using the type function.

5
2.1 Data Structure - Strings

A string is a sequence of characters, such as “Hello World” we saw in chapter


1. Strings are surrounded by either single or double quotation marks.
Note that a blank space, ” “, between “Hello” and “World” is also a type str.
Any symbol can be a char, even the ones that have been reserved for
operators.
Note that as a str, they do not perform the same function. Although they look
the same, Python interprets them completely differently.

6
2.1 Data Structure - Strings

Example: Create an empty string. Verify that the empty string is a str.

A string is an array of characters, therefore it has length to indicate the size of the string.
For example, we could check the size of the string by using the built-in function len.

7
2.1 Data Structure - Strings

Strings also have indexes to indicate the location of each character, so that we could
easily find out some character. The index of the position start with 0, as shown in the
following picture.

We could get access to any character by using a bracket and the index of the position. For
example, if we want to get the character ‘W’, then we need to do:

We could also select a sequence as well using string slicing. For example, if we want to get
the “World”, we could do the following command.

8
2.1 Data Structure - Strings
You can also use negative index when slice the strings, which means counting from the
end of the string. For example, -1 means the last character, -2 means the 2nd to last and
so on.

w.upper() ->
w.count("l") ->
w.replace("World", "UEH") ->
len(w) ->

9
2.2 Data Structure - Lists
We saw strings in the previous section that could hold a sequence of characters. Now, let’s
see a more versatile sequential data structure in Python - Lists. The way to define it is to
use a pair of brackets [ ], and the elements within it are separated by commas. A list could
hold any type of data: numerical, or strings or other types. For example:

10
2.2 Data Structure - Lists

11
2.2 Data Structure - Lists
Topic Explanation Example

Creating a list A list is an ordered collection of my_list = [1, 2, 3, 4,


elements. You can create a list using
square brackets [].
5]

Adding and - Adding: Use append() to add an my_list.append(6)


element to the end of the list. my_list.remove(3)
Removing - Removing: Use remove() or pop() to
Elements remove elements.

Accessing Access elements in a list by their first_element =


Elements index. Python lists use zero- my_list[0]
based indexing.

List Functions - len(): Returns the number of elements. len(my_list)


- index(): Returns the index of the first my_list.index(4)
occurrence of a value. my_list.count(2)
- count(): Returns the count of a value. my_list.sort()
- sort(): Sorts the list in ascending order. 12
2.3 Data Structure - Tuples
Let’s learn one more different sequence data structure in Python - Tuples. It is usually
defined by using a

pair of parentheses ( ) , and its elements are separated by commas. For example:

What’s the difference between lists and tuples?

Tuples are IMMUTABLE

13
2.4 Data Structure - Sets
Another data type in Python is sets. It is a type that could store an unordered collection
with no duplicate elements. It is also support the mathematical operations like union,
intersection, difference, and symmetric difference. It is defined by using a pair of braces
{ }, and its elements are separated by commas.

14
2.4 Data Structure - Set
Topic Explanation Example

Creating a Set A set is an unordered collection of unique my_set = {1, 2, 3, 4, 5}


elements. You can create a set using curly braces another_set = set([1, 2, 3])
{} or the set() constructor.

Adding an Add an element to a set using the add() method. If my_set.add(6)


the element already exists, the set remains
Element unchanged.

Accessing Sets are unordered, can't access for elem in my_set:print(elem)


Elements elements by index. Check for 6 in my_set
existence or loop through the set.

Set Functions - union(): Returns a set that is the union of two my_set.union(another_set)
sets. my_set.intersection(another_set)
- intersection(): Returns the common elements my_set.difference(another_set)
between two sets.
- difference(): Returns the difference between
two sets.
15
2.5 Data Structure - Dictionaries
Now we will introduce you a new and useful type - Dictionaries. It is a mapping type,
which makes it a totally different type than the ones we talked before. Instead of using a
sequence of numbers to index the elements (such as lists or tuples), dictionaries are
indexed by keys, which could be a string, number or even tuple (but not list). A dictionary
is a key-value pairs, and each key maps to a corresponding value. It is defined by using a
pair of braces { }, while the elements are a list of comma separated key:value pairs (note
the key:value pair is separated by the colon, with key at front and value at the end).

16
2.5 Data Structure - Dictionaries
Now we will introduce you a new and useful type - Dictionaries. It is a mapping type,
which makes it a totally different type than the ones we talked before. Instead of using a
sequence of numbers to index the elements (such as lists or tuples), dictionaries are
indexed by keys, which could be a string, number or even tuple (but not list). A dictionary
is a key-value pairs, and each key maps to a corresponding value. It is defined by using a
pair of braces { }, while the elements are a list of comma separated key:value pairs (note
the key:value pair is separated by the colon, with key at front and value at the end).

17
2.5 Data Structure - Dictionaries
Topic Explanation Example

Creating a dictionary A dictionary is an unordered collection of key-value pairs. It my_dict = {“name":”John", “age":
is created using curly braces {}. 30, “city": “New York"}

Adding and Removing Key-Value Pairs - Adding: Assign a value to a new key. my_dict["job"] = "Engineer"
- Removing: Use del or pop() to remove a key-value pair. del my_dict["age"]

Accessing Elements Values can be accessed using their corresponding key. You my_dict["name"]
can also use the get() method to safely retrieve values. my_dict.get("city")

Dictionary Functions - keys(): Returns a view object displaying all keys in the my_dict.keys()
dictionary. my_dict.clear()
- clear(): Removes all items from the dictionary. my_dict.copy()
- copy(): Returns a shallow copy of the dictionary. my_dict.values()
- values(): Returns a view object displaying all values. my_dict.items()
- items(): Returns a view object displaying all key-value my_dict.get("name")
pairs.
- get(): Retrieves the value associated with a given key.

18
End

Thanks for listening

19

You might also like