List
List
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store
collections of data, the other 3 are Tuple, Set, and Dictionary, all
with different qualities and usage.
Lists are created using square brackets:
Example
Create a List:
thislist = ["apple" , "banana" , "cherry" ]
print (thislist)
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/Mutable
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))
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))
Insert Items
To insert a new list item, without replacing any of the existing values,
we can use the insert( ) method.
The insert( ) method inserts an item at the specified index:
Example
Insert "watermelon" as the third item:
thislist = ["apple" , "banana" , "cherry" ]
thislist.insert(2 , "watermelon" )
print (thislist)
Python - Add List Items
Append Items
To add an item to the end of the list, use the append( ) method:
Example
Using the append( ) method to append an item:
thislist = ["apple" , "banana" , "cherry" ]
thislist.append("orange" )
print (thislist)
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.
Example
Remove the last item:
thislist = ["apple" , "banana" , "cherry" ]
thislist.pop()
print (thislist)
The del keyword also removes the specified index:
Example
Remove the first item:
thislist = ["apple" , "banana" , "cherry" ]
del thislist[0 ]
print (thislist)
The del keyword can also delete the list completely.
Example
Delete the entire list:
thislist = ["apple" , "banana" , "cherry" ]
del thislist
Example
Clear the list content:
thislist = ["apple" , "banana" , "cherry" ]
thislist.clear()
print (thislist)
Python - Loop Lists
Loop Through a List
You can loop through the list items by using a fo r loop:
Example
Print all items in the list, one by one:
thislist = ["apple" , "banana" , "cherry" ]
for x in thislist:
print (x)
Learn more about for loops in our Python For Loops Chapter.
Example
fruits = ["apple" , "banana" , "cherry" , "kiwi" , "mango" ]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print (newlist)
With list comprehension you can do all that with only one line of code:
Example
fruits = ["apple" , "banana" , "cherry" , "kiwi" , "mango" ]
newlist = [x for x in fruits if "a" in x]
print (newlist)
The Syntax
newlist = [expression for item in iterable if condition == True ]
The return value is a new list, leaving the old list unchanged.
Condition
The condition is like a filter that accepts only the items that valuates
to True.
Example
Only accept items that are not "apple":
newlist = [x for x in fruits if x != "apple" ]
The condition if x != "apple" will return Tru e for all elements other
than "apple",making the new list contain all fruits except "apple".
The condition is optional and can be omitted:
Example
With no if statement:
newlist = [x for x in fruits]
Iterable
The iterable can be any iterable object, like a list, tuple, set
etc.
Example
You can use the range( ) function to create an iterable:
newlist = [x for x in range (10 )]
Same example, but with a condition:
Example
Accept only numbers lower than 5:
newlist = [x for x in range (10 ) if x < 5 ]
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:
Example
Set the values in the new list to upper case:
newlist = [x.upper() for x in fruits]
You can set the outcome to whatever you like:
Example
Set all values in the new list to 'hello':
newlist = ['hello' for x in fruits]
The expression can also contain conditions, not like a filter, but
as a way to manipulate the outcome:
Example
Return "orange" instead of "banana":
newlist = [x if x != "banana" else "orange" for x in fruits]
The expression in the example above says:
"Return the item if is not banana, if it is banana 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:
thislist = ["orange" , "mango" , "kiwi" , "pineapple" , "banana" ]
thislist.sort()
print (thislist)
Example
Sort the list numerically:
thislist = [100 , 50 , 65 , 82 , 23 ]
thislist.sort()
print (thislist)
Sort Descending
To sort descending, use the keyword argument reverse = Tru e :
Example
Sort the list descending:
thislist = ["orange" , "mango" , "kiwi" , "pineapple" , "banana" ]
thislist.sort(reverse = True )
print (thislist)
Example
Sort the list descending:
thislist = [100 , 50 , 65 , 82 , 23 ]
thislist.sort(reverse = True )
print (thislist)