Module 2 - Data Scalability and Analytics
Module 2 - Data Scalability and Analytics
Introduction
#19
Python Lists
Python Collections (Arrays)
There are four collection data types in the Python programming language:
List
Output:
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last
item, -2 refers to the second last item etc.
Python
Introduction
#20
Range of Indexes
You can specify a range of indexes by specifying where to start and where
to end the range.
When specifying a range, the return value will be a new list with the
specified items.
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Output:
By leaving out the start value, the range will start at the first item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
Output:
Python
Introduction
#21
You can loop through the list items by using a for loop:
Output:
Output:
List Length
To determine how many items a list has, use the len() function:
Python
Introduction
#22
Output:
Add Items
To add an item to the end of the list, use the append() method.
Remove Item
The pop() method removes the specified index, (or the last item if index
is not specified).
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will
only be a reference to list1, and changes made in list1 will
automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List
method copy().
Output:
Output:
Another way to join two lists are by appending all the items from list2 into
list1, one by one.
Or you can use the extend() method, which purpose is to add elements
from one list to another list.
Output:
Python has a set of built-in methods that you can use on lists.
Python Tuples
Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
You can access tuple items by referring to the index number, inside
square brackets:
Python
Introduction
#25
Output:
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last
item, -2 refers to the second last item etc.
Range of Indexes
You can specify a range of indexes by specifying where to start and where
to end the range.
When specifying a range, the return value will be a new tuple with the
specified items.
Specify negative indexes if you want to start the search from the end of
the tuple:
Output:
Python
Introduction
#26
You can loop through the tuple items by using a for loop.
Tuple Length
To determine how many items a tuple has, use the len() method.
Add Items