0% found this document useful (0 votes)
41 views

17 Python Lists Tuples

This document discusses lists and tuples in Python. It provides information on: - Lists are ordered, changeable collections that allow duplicate elements and can contain elements of different data types. Tuples are ordered and unchangeable collections that also allow duplicate elements. - Common list operations include accessing items by index, checking if an item exists, modifying/adding/removing items, joining lists, sorting lists, and looping through lists. - Common tuple operations include accessing items by index and checking if an item exists. Tuples are immutable so their items cannot be modified. - Both lists and tuples are useful for storing collections of multiple items in Python. The main differences are that lists are mutable while tuples are

Uploaded by

Tech Buster
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

17 Python Lists Tuples

This document discusses lists and tuples in Python. It provides information on: - Lists are ordered, changeable collections that allow duplicate elements and can contain elements of different data types. Tuples are ordered and unchangeable collections that also allow duplicate elements. - Common list operations include accessing items by index, checking if an item exists, modifying/adding/removing items, joining lists, sorting lists, and looping through lists. - Common tuple operations include accessing items by index and checking if an item exists. Tuples are immutable so their items cannot be modified. - Both lists and tuples are useful for storing collections of multiple items in Python. The main differences are that lists are mutable while tuples are

Uploaded by

Tech Buster
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

IT Automation

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.

- List is a collection which is ordered and changeable. Allows duplicate members.


- Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
- Set is a collection which is unordered and unindexed. No duplicate members.
- Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
Lists
• Lists are created using square brackets:
- Ex: myList = [] #initializing an empty list
- Ex: fruit = ["apple", "banana", "cherry"]

• List are ordered, indexed, changeable, and allow duplicate values.

• 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.

• Checking if an item exists in a list:


- Use the in keyword - returns True or False
- Example:
fruitList = ["apple", "banana", "cherry"]
if "apple" in  fruitList :
   print("'apple' is in the fruit list")

• 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[1] = "blackcurrant“ # Changes “banana” to “blackcurrant”

fruitList[1:3] = ["blackcurrant", "watermelon"] # Using a range in the index – 1 included, 3 is


not;
# Changes "banana", "cherry“ to
# "blackcurrant", "watermelon”
Adding List Items
• To insert a new item we use the insert() method. It inserts an item at the specified, indexed, position.

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.

frutiList.append("orange") # inserts the item at the end to the end


Joining Lists
• There are a couple ways to join two or more lists in Python.

• By using the + operator


nonTropical = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
fruit = nonTropical + tropical #List contains: [‘apple‘, ‘banana‘, ‘cherry‘,
‘mango‘, ‘pineapple‘, ‘papaya‘]

• By using the extend() method


fruit = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
fruit.extend(tropical)
print(fruit) # List contains:['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya’]

- 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.

- ascending is the default sorting order

fruit = ["orange", "mango", "kiwi", "pineapple", "banana"] # List with string values


fruit.sort()

numbers = [100, 50, 65, 82, 23] # List with numeric values


numbers.sort()

- To sort descending, use the parameter reverse = True

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

- Without an index, the pop() method removes the last item


fruitList.pop() # removes “apple” at the end

• The clear() method empties the list


fruitList.clear() # The List object itself is not deleted

• del keyword can also delete the list completely


del fruitList # Deletes the whole List object
Looping through a List
• We can process values saved in a List by using a for loop or a while loop.

• Ex. fruitList = ["apple", "banana", "cherry"]

- Using a for loop:

for x in fruitList:
print(x) # printing the List element from the current loop iteration

- Using a while loop:

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")

• Accessing items in a Tuple: by using the zero-based index


- Ex:
fruit = ("apple", "banana", "cherry")
print(fruit[1]) - prints out banana

- 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 = ("apple", "banana", "cherry") # starting with a tuple

y = list(x) # converting the tuple to a list amd saving it to a new variable


y[1] = "kiwi“ # changing the list (the element at the 2nd position

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.

• Ex. fruitTuple = ("apple", "banana", "cherry“)

- Using a for loop:

for x in fruitTuple: #iterates through the items and prints the values
print(x)

• Using a while loop:

i = 0

while i < len(fruitTuple):


print(fruitTuple[i])
i = i + 1
Lists vs. Tuples
• How do we decide which data type to use - a list or a tuple? – The answer will depend on the task at
hand.
• In general, lists are used more often, mostly because they are dynamic in nature, while tuples are
unchangeable and, therefore, fixed in size.
• Tuples are faster than lists when being processed in a loop.
• If you know that you are to work with a constant set of data, which you know you will not need to
change, you may opt to go with a tuple, for performance reasons.
String join() method
• The join() string method provides an easy way to join (concatenate) elements of an iterable object into one string.
• It works on strings, lists, tuples, sets, and dictionaries.
• It joins each element of an iterable by a string separator - the string on which the join() method is called, and returns
the concatenated string.
• For the method to work all elements of the iterable object need to be strings.

• Example using join() with a list:


numList = ['1', '2', '3', '4’]
separator = ‘, ‘
print(numList) #Output: ['1', '2', '3', '4’]
print(separator.join(numList)) #Output is: 1, 2, 3, 4 - as one string

• Example using join() with a tuple:


numTuple = ('1', '2', '3', ‘4’)
separator = ', ‘
print(separator.join(numTuple))
Questions?
References
• https://www.w3schools.com/python/python_lists.asp
• https://www.w3schools.com/python/python_lists_access.asp
• https://www.w3schools.com/python/python_lists_change.asp
• https://www.w3schools.com/python/python_lists_add.asp
• https://www.w3schools.com/python/python_lists_remove.asp
• https://www.w3schools.com/python/python_lists_loop.asp
• https://www.w3schools.com/python/python_lists_sort.asp
• https://www.w3schools.com/python/python_lists_copy.asp
• https://www.w3schools.com/python/python_lists_join.asp
• https://www.w3schools.com/python/python_lists_methods.asp
• https://www.w3schools.com/python/exercise.asp?filename=exercise_lists1
• https://www.programiz.com/python-programming/methods/string/join
• https://www.w3schools.com/python/ref_string_join.asp

You might also like