Lists - zamaniamin/python GitHub Wiki
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.
Create a List:
this_list = ["apple", "banana", "cherry"]
print(this_list)
empty_list = []
empty_list2 = list()
List properties
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.
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. Lists allow duplicate values.
this_list = ["apple", "banana", "cherry", "apple", "cherry"]
print(this_list)
Items Data Types
List items can be of any data type.
string, int and boolean data types:
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, use the
len()
function:
Print the number of items in the list:
this_list = ["apple", "banana", "cherry"]
print(len(this_list))
Type
From Python's perspective, lists are defined as objects with the data type
list
# <class 'list'>
# What is the data type of list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
List Constructor
It is also possible to use the
list()
constructor when creating a new list.
Using the list()
constructor to make a List:
this_list = list(("apple", "banana", "cherry")) # note the double round-brackets
print(this_list)
this_list2 = list(range(3, 10)) # [3,4,5,6,7,8,9]
Access List Items
List items are indexed and you can access them by referring to the index number.
Print the second item of the list:
this_list = ["apple", "banana", "cherry"]
print(this_list[1])
Negative Indexing
Negative indexing means start from the end.
-1
refers to the last item,-2
refers to the second last item etc.
Print the last item of the list:
this_list = ["apple", "banana", "cherry"]
print(this_list[-1])
Range of Indexes (Slices)
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.
list[ start : stop : step ]
Return the third, fourth, and fifth item:
this_list = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
Note: The search will start at index 2 (included) and end at index 5 (not included).
print(this_list[2:5])
By leaving out the start value, the range will start at the first item.
This example returns the items from the beginning to, but NOT including, "kiwi":
this_list = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(this_list[:4])
By leaving out the end value, the range will go on to the end of the list.
This example returns the items from "cherry" to the end:
this_list = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(this_list[2:])
more example:
slice1 = 'superduper'[3:7] # return: 'erdu'
slice2 = 'superduper'[3:7:2] # return: 'ed'
stuff = ['c', 6, 's', 9, 't', 6]
stuff = stuff[0:5:2] # return: ['c','a','t']
nums = [4, 5, 6, 7]
nums[1:3] = ['a', 'b'] # returns: [4,'a','b',7]
nums[1:3] = ['a', 'b', 'c', 'd'] # returns: [4, 'a', 'b', 'c', 'd', 7]
nums[1:5] = [5] # returns: [4, 5, 7]
Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the list.
This example returns the items from "orange" (-4) to, but NOT including "mango" (-1):
this_list = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(this_list[-4:-1])
Check if Item Exists
To determine if a specified item is present in a list use the
in
keyword.
Check if "apple" is present in the list:
this_list = ["apple", "banana", "cherry"]
if "apple" in this_list:
print("Yes, 'apple' is in the fruits list")
Change Item Value
To change the value of a specific item, refer to the index number.
Change the second item:
this_list = ["apple", "banana", "cherry"]
this_list[1] = "blackcurrant"
print(this_list)
Change a Range of Item Values
To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values.
Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":
this_list = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
this_list[1:3] = ["blackcurrant", "watermelon"]
print(this_list)
If you insert more items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly.
Change the second value by replacing it with two new values:
this_list = ["apple", "banana", "cherry"]
this_list[1:2] = ["blackcurrant", "watermelon"]
print(this_list)
If you insert less items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly.
Change the second and third value by replacing it with one value:
this_list = ["apple", "banana", "cherry"]
this_list[1:3] = ["watermelon"]
print(this_list)
Insert Items
To insert a new list item, without replacing any of the existing values, we can use the
insert()
method. Theinsert()
method inserts an item at the specified index.
Insert "watermelon" as the third item:
this_list = ["apple", "banana", "cherry"]
this_list.insert(2, "watermelon")
print(this_list)
# Note: As a result of the example above, the list will now contain 4 items.
Append Items
To add an item to the end of the list, use the append() method.
this_list = ["apple", "banana", "cherry"]
print(this_list)
this_list.append("orange")
print(this_list)
Extend List
To append elements from another list to the current list, use the
extend()
method. The elements will be added to the end of the list.
Add the elements of tropical to this_list:
this_list = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
this_list.extend(tropical)
print(this_list)
Add Any Iterable
extend()
method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries etc.).
Add elements of a tuple to a list:
this_list = ["apple", "banana", "cherry"]
this_tuple = ("kiwi", "orange")
this_list.extend(this_tuple)
print(this_list)
Remove Specified Item
The
remove()
method removes the specified item.
# Remove "banana":
this_list = ["apple", "banana", "cherry"]
this_list.remove("banana")
print(this_list)
Remove Specified Index
The
pop()
method removes the specified index.
# Remove the second item:
this_list = ["apple", "banana", "cherry"]
this_list.pop(1)
print(this_list)
If you do not specify the index, the
pop()
method removes the last item.
# Remove the last item:
this_list = ["apple", "banana", "cherry"]
this_list.pop()
print(this_list)
The
del
keyword also removes the specified index.
# Remove the first item:
this_list = ["apple", "banana", "cherry"]
del this_list[0]
print(this_list)
The
del
keyword can also delete the list completely.
# Delete the entire list:
this_list = ["apple", "banana", "cherry"]
del this_list
Clear the List
The
clear()
method empties the list. The list still remains, but it has no content.
Clear the list content:
this_list = ["apple", "banana", "cherry"]
this_list.clear()
print(this_list)
Loop Through a List
You can loop through the list items by using a
for
loop.
Print all items in the list, one by one:
this_list = ["apple", "banana", "cherry"]
for x in this_list:
print(x)
evens = [1, 2, 3, 4]
print(4 in evens) # output: True
print(5 in evens) # output: False
Loop Through the Index Numbers
You can also loop through the list items by referring to their index number. Use the
range()
andlen()
functions to create a suitable iterable.
Print all items by referring to their index number:
this_list = ["apple", "banana", "cherry"]
for i in range(len(this_list)):
print(this_list[i])
Loop Using a While
You can loop through the list items by using a while loop. Use the
len()
function to determine the length of the list, then start at0
and loop your way through the list items by referring to their indexes. Remember to increase the index by1
after each iteration.
Print all items, using a while loop to go through all the index numbers:
this_list = ["apple", "banana", "cherry"]
i = 0
while i < len(this_list):
print(this_list[i])
i = i + 1
Looping Using List Comprehension
List Comprehension offers the shortest syntax for looping through lists.
A shorthand for loop that will print all items in a list:
this_list = ["apple", "banana", "cherry"]
[print(x) for x in this_list]
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name. Without list comprehension you will have to write a for statement with a conditional test inside:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
new_list = []
for x in fruits:
if "a" in x:
new_list.append(x)
With list comprehension you can do all that with only one line of code:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
new_list = [x for x in fruits if "a" in x]
print(new_list)
The Syntax
new_list = [expression
for
itemin
iterableif
condition == True]. The return value is a new list, leaving the old list unchanged.
Condition
The condition is like a filter that only accepts the items that valuate to True.
Only accept items that are not "apple":
new_list = [x for x in fruits if x != "apple"]
print(new_list)
The condition
if x != "apple"
will returnTrue
for all elements other than"apple"
, making the new list contain all fruits except"apple"
.
The condition is optional and can be omitted. With no if statement:
new_list = [x for x in fruits]
print(new_list)
Iterable
The iterable can be any iterable object, like a
list
,tuple
,set
etc. You can use therange()
function to create an iterable:
new_list = [x for x in range(10)]
print(new_list)
Same example, but with a condition, Accept only numbers lower than 5:
new_list = [x for x in range(10) if x < 5]
print(new_list)
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.
Set the values in the new list to upper case:
new_list = [x.upper() for x in fruits]
print(new_list)
You can set the outcome to whatever you like, Set all values in the new list to 'hello':
new_list = ['hello' for x in fruits]
print(new_list)
The expression can also contain conditions, not like a filter, but as a way to manipulate the outcome:
# Return "orange" instead of "banana":
new_list = [x if x != "banana" else "orange" for x in fruits]
# The expression in the example above says:
# Return the item if it is not banana, if it is banana return orange
Sort List Alphanumerically
List objects have a
sort()
method that will sort the list alphanumerically, ascending, by default.
Sort the list alphabetically:
this_list = ["orange", "mango", "kiwi", "pineapple", "banana"]
this_list.sort()
print(this_list)
# Sort the list numerically:
this_list = [100, 50, 65, 82, 23]
this_list.sort()
print(this_list)
Sort Descending
To sort descending, use the keyword argument reverse = True.
Sort the list descending:
this_list = ["orange", "mango", "kiwi", "pineapple", "banana"]
this_list.sort(reverse=True)
print(this_list)
this_list = [100, 50, 65, 82, 23]
this_list.sort(reverse=True)
print(this_list)
Customize Sort Function
You can also customize your own function by using the keyword argument key = function. The function will return a number that will be used to sort the list (the lowest number first).
Sort the list based on how close the number is to 50:
def my_func(n):
return abs(n - 50)
this_list = [100, 50, 65, 82, 23]
this_list.sort(key=my_func)
print(this_list)
Case Insensitive Sort
By default the
sort()
method is case sensitive, resulting in all capital letters being sorted before lower case letters.
Case-sensitive sorting can give an unexpected result:
this_list = ["banana", "Orange", "Kiwi", "cherry"]
this_list.sort()
print(this_list)
Luckily we can use built-in functions as key functions when sorting a list. So if you want a case-insensitive sort function, use
str.lower
as a key function.
Perform a case-insensitive sort of the list:
this_list = ["banana", "Orange", "Kiwi", "cherry"]
this_list.sort(key=str.lower)
print(this_list)
Reverse Order
What if you want to reverse the order of a list, regardless of the alphabet? The
reverse()
method reverses the current sorting order of the elements.
Reverse the order of the list items:
this_list = ["banana", "Orange", "Kiwi", "cherry"]
this_list.reverse()
print(this_list)
Copy a List
You cannot copy a list simply by typing
list2 = list1
, becauselist2
will only be a reference tolist1
, and changes made inlist1
will automatically also be made inlist2
. There are ways to make a copy, one way is to use the built-in List methodcopy()
.
Make a copy of a list with the copy() method:
this_list = ["apple", "banana", "cherry"]
mylist = this_list.copy()
print(mylist)
Deep copy
The
deepcopy()
method will make a copy of a list and any nested objects contained inside that list.
import copy
list1 = [1, 2, ['a', 'b'], 3]
list2 = copy.deepcopy(list1)
Another way to make a copy is to use the built-in method
list()
Make a copy of a list with the list() method:
this_list = ["apple", "banana", "cherry"]
mylist = list(this_list)
print(mylist)
def change_main_list(main_list):
copy_list = main_list
print(main_list is copy_list) # True
def dont_change_main_list(main_list):
copy_list = main_list.copy()
print(main_list is copy_list) # False
Join Lists
There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the
+
operator.
Join two list:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Multiplication
Copy list and join again:
print([1, 2, 3] * 5) # [1,2,3,1,2,3]
Another way to join two lists is by appending all the items from
list2
intolist1
, one by one.
Append 'list2' into 'list1':
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Or you can use the
extend()
method, which purpose is to add elements from one list to another list.
Use the extend()
method to add list2
at the end of list1
:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
List Methods
Python has a set of built-in methods that you can use on lists.
# Method Description
# append() Adds an element at the end of the list
# clear() Removes all the elements from the list
# copy() Returns a copy of the list
# count() Returns the number of elements with the specified value
# extend() Add the elements of a list (or any iterable), to the end of the current list
# index() Returns the index of the first element with the specified value
# insert() Adds an element at the specified position
# pop() Removes the element at the specified position
# remove() Removes the item with the specified value
# reverse() Reverses the order of the list
# sort() Sorts the list
Nested List
nums = [1, 2, 3, 4, [5, 6]]
print(nums[4]) # output: [5,6]
print(nums[4][1]) # output: 6
super_nested = [[[[[[[](/zamaniamin/python/wiki/[[[[[[)]]]]]]
loop nested list:
couples = [
['Beyonce', 'Jay-Z'],
['Johnny', 'June'],
['John', 'Yoko'],
['Will', 'Jada']
]
for couple in couples:
for person in couple:
print(f'sending invite to "{person}"')
Comparing list
Use ==
to compare the content inside two lists. do they hold same values?
print([1, 2, 3] == [1, 2, 3]) # output: True
use
is
to compare the identity of two lists. are they the same "container" in memory?
print([1, 2, 3] is [1, 2, 3]) # output: False
evens = [1, 2, 3]
evens2 = evens
print(evens is evens2) # output: True
Unpacking
We can use "unpacking" values from a list into specific variables.
In this example, the first value in the list is stored in a variable called first.
the second value is stored in a variable called last.
the third value is stored in a variable called age.
user = ['Lucas', 'Bucky', '42']
first, last, age = user
print(f'{first} {last} {age}') # output: Lucas Bucky 42
user = ['Lucas', 'Bucky', '42']
*name, age = user
print(f'{name} {age}') # output: ['Lucas', 'Bucky'] 42