Python Lesson 6
Python Lesson 6
Python Lists
Lesson 6 Content
• Python Lists • Python - Loop Lists
• List • Loop Through a List
• List Items • Loop Through the Index Numbers
• Ordered • Using a While Loop
• Changeable • Looping Using List Comprehension
• Allow Duplicates • Python - List Comprehension
• List Length
• List Items - Data Types • The Syntax
• type() • Condition
• The list() Constructor • Iterable
• Python Collections (Arrays) • Expression
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that order will not
change.
If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the order of the items
will not change.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has been
created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
List Items - Data Types
List items can be of any data type:
Example
String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
type()
From Python's perspective, lists are defined as objects with the data type 'list': <class 'list'>
Example
What is the data type of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
*Set items are unchangeable, but you can remove and/or add items whenever you like.
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
When choosing a collection type, it is useful to understand the properties of that type. Choosing the
right type for a particular data set could mean retention of meaning, and, it could mean an increase in
efficiency or security.
Python - Access List Items
Access Items
List items are indexed and you can access them by referring to the index number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Note: The first item has index 0.
Negative Indexing
Negative indexing means start from the end -1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
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.
Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will By leaving out the end value, the range will go on
start at the first item: to the end of the list:
Example Example
This example returns the items from the This example returns the items from "cherry" to
beginning to, but NOT including, "kiwi": the end:
thislist = ["apple", "banana", "cherry", "orange", thislist = ["apple", "banana", "cherry", "orange", "kiwi",
"kiwi", "melon", "mango"] "melon", "mango"]
print(thislist[:4]) print(thislist[2:])
Note: The length of the list will change when the number of items inserted does not match the number
of items replaced.
Insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:
Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
Note: As a result of the examples above, the lists will now contain 4 items.
Extend List
To append elements from another list to the current list, use the extend() method.
Example
Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
The elements will be added to the end of the list.
Condition Iterable
The condition is like a filter that only accepts the The iterable can be any iterable object, like a
items that valuate to True. list, tuple, set etc.
Example Example
Only accept items that are not "apple": You can use the range() function to create an
newlist = [x for x in fruits if x != "apple"] iterable:
newlist = [x for x in range(10)]
The condition if x != "apple" will return True for
all elements other than "apple", making the new list Same example, but with a condition:
contain all fruits except "apple". Example
The condition is optional and can be omitted: Accept only numbers lower than 5:
Example newlist = [x for x in range(10) if x < 5]
With no if statement:
newlist = [x for x in fruits]
Expression
The expression is the current item in the iteration, but it is also the outcome, which you can manipulate
before it ends up like a list item in the new list:
The expression can also contain conditions, not like a
Example
filter, but as a way to manipulate the outcome:
Set the values in the new list to upper case:
Example
newlist = [x.upper() for x in fruits]
You can set the outcome to whatever you like: Return "orange" instead of "banana":
Example newlist = [x if x != "banana" else "orange" for x in fruits]
Set all values in the new list to 'hello': The expression in the example above says:
"Return the item if it is not banana, if it is banana
newlist = ['hello' for x in fruits]
return orange".
Python - Sort Lists
Sort List Alphanumerically
List objects have a sort() method that will sort the list alphanumerically, ascending, by default:
Example
Sort the list alphabetically: Sort the list numerically:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist = [100, 50, 65, 82, 23]
thislist.sort() thislist.sort()
print(thislist) print(thislist)
Sort Descending
To sort descending, use the keyword argument reverse = True:
Example
Sort the list descending: Sort the list descending:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True) thislist.sort(reverse = True)
print(thislist) print(thislist)
There are ways to make a copy, one way is to use the built-in List method copy().
Example
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
list1.extend(list2)
print(list1)