17 Python Lists Tuples
17 Python Lists Tuples
INFO8025
Conestoga College
IT AUTOMATION – INFO 8025
Topic 17 – Lists & Tuples
Objectives
• Collection data types:
- Lists
- Tuples
• Hands-on Time
Collections
• Python has 4 built-in collection data types that are used for storing multiple items into a single variable:
- List
- Tuple
- Set
- Dictionary
• Each has different qualities and usage: ordered/unordered, changeable/unchangeable, allows/does not
allow duplicate elements.
• Ordered
- the items have a defined order, and that order does not change: if adding new items to a list,
they will be placed at the end
• Indexed
- First item has index [0], the second item has index [1], and so on.
• Changeable
- we can change, add, and remove items in a list after it has been created
• Allows Duplicates
- Since lists are indexed, lists can have items with the same value:
- Ex: fruit = ["apple", "banana", "cherry", "apple", "cherry"]
List Items Data Types
• List Items can be of any data type.
• Examples:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
list4 = ["abc", 34, True, 40, "male"]
List Length
• To determine how many items a list has, we use the len() function.
• Example:
fruitList = ["apple", "banana", "cherry"]
print(len(fruitList)) #Output: 3
Accessing List Items
• Accessing list items by using the zero-based index:
fruitList = ["apple", "banana", "cherry“, “lemon", “watermelon", "cherry"]
print(fruitList[1]) # Prints out the second item in the list
print(fruitList[-1]) # Negative indexing means start from the end; prints out the last item
print(fruitList[2:5]) # The range: will print out the items located at the position 3, 4, and 5. The
# search starts at index 2 (included) and ends at index 5 (not included).
- When specifying a range, the return value will be a new List containing the specified items.
• Can use the not in keyword to check if an item does not exist in a list.
Modifying Items in a List
• To modify a value of a list item, make use of the index number:
fruitList = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
fruitList = ["apple", "banana", "cherry"]
fruitList.insert(2, "watermelon") # inserts the item in the third position (after “banana”)
• To add a new item to the end of the list, we use the append() method.
- extend() method can be used to add any other type of a collection to a list as well: a tuple, set, or a
dictionary. - extend() can join two objects only
Sorting a List
• The sort() method will sort a list.
fruit = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruit.sort(reverse = True)
• The reverse() method reverses the current order of the elements (regardless of the alphabet)
fruit = ["banana", "Orange", "Kiwi", "cherry"]
fruit.reverse() # will be reversed to ['cherry', 'Kiwi', 'Orange', 'banana']
Removing List Items
• remove() method removes an item by value.
fruitList = ["apple", "banana", "cherry“, “apple”]
fruitList.remove("apple") # using the value of the element; only the first occurrence is removed
• pop() method and del keyword both remove the item by index.
fruitList.pop(1) # Removes 2nd item
del fruitList[1] # Removes 2nd item
del fruitList[0:2] # Removes a range of elements: 1st and 2nd element
for x in fruitList:
print(x) # printing the List element from the current loop iteration
i=0 # initializing the variable that will be used as a counter in the loop
while i < len(fruitList):
print(fruitList[i]) # using i as the List index, to reference the List element in the current
iteration
i+=1 # incrementing the loop counter by 1
Additional List Methods
• count() method return the number of times a specified value appears in the list
Ex:
fruit = [‘cherry’, 'apple', 'banana', 'cherry’]
x = fruit.count("cherry") # Returns the # of times “cherry” appears in fruit: 2
• index() method returns the position (index) of the first occurrence of the specified value
Ex:
fruit = ['apple', 'banana', 'cherry’, ‘lemon’, ‘cherry’]
x = fruit.index("cherry") # Returns the position of the 1st ‘cherry’ value: 2
Tuples
• A tuple is a collection which is ordered, unchangeable, and allows duplicate values.
• In Python tuples are written with round brackets.
- Ex: fruit = ("apple", "banana", "cherry")
- Negative indexing means starting from the end; index -1 references the last item
-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
- Ex:
fruitTuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(fruitTuple[2:5]) # will start at index 2 (included) and end at index 5 (not included).
Tuple
• Checking if an item exists in a tuple:
- Use the in keyword; it returns True or False
fruitTuple = ("apple", "banana", "cherry“)
if "apple" in fruitTuple :
print("'apple' is in the fruit tuple")
• Can use the not in keyword to check if an item does not exist in a tuple.
Tuple Items Data Types
• Tuple Items can be of any data type.
• Examples:
tuple1 = ("apple", "banana", "cherry“)
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
tuple4 = ("abc", 34, True, 40, "male“)
Tuples are unchangeable (immutable)
• This means that we cannot change its existing values, add new values, remove values.
• A workaround: can convert a tuple into a list, change the list, and convert the list back into a tuple
x = tuple(y) # converting the list back to the tuple, and reassigning it to the original value.
Tuple Length
• To determine how many items a tuple has, we use the len() function.
• Example:
fruitTuple = ("apple", "banana", "cherry“)
print(len(fruitTuple)) #Output: 3
Joining Tuples
• To join two or more tuples we can use the + operator:
nonTropical = ("apple", "banana", "cherry“)
tropical = ("pineapple", "papaya“)
fruit = nonTropical + tropical # The tuple contains: (‘apple‘, ‘banana‘, ‘cherry‘, ‘pineapple‘, ‘papaya‘)
Additional Tuple Methods
• count() method returns the number of times a specified value appears in the tuple
Ex:
fruit = (‘cherry’, 'apple', 'banana', 'cherry’)
x = fruit.count("cherry") # Returns the # of times “cherry” appears in fruit: 2
• index() method returns the position (index) of the first occurrence of an element with the specified value
Ex:
fruits = ('apple', 'banana', 'cherry’, lemon, ‘cherry’)
x = fruits.index("cherry") # Returns the position of the 1st ‘cherry’ value: 2
Looping through a Tuple
• To loop through a tuple we can use a for loop or a while loop.
for x in fruitTuple: #iterates through the items and prints the values
print(x)
i = 0