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.
There are four collection data types in the Python programming language:
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, unchangeable*, and unindexed. No duplicate members.
Dictionary is a collection which is ordered** and changeable. No duplicate members.
*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.
Access List Items
List items are indexed and you can access them by referring to the index number:
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.
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":
Note: The length of the list will change when the number of items inserted does not match the number of items replaced. 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:
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: Insert "watermelon" as the third item:
You can loop through the list items by using a for loop:
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"] for x in thislist: print(x)
The iterable created in the example above is [0, 1, 2].
Using a While Loop
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 at 0 and loop your way through the list items by refering to their indexes. Remember to increase the index by 1 after each iteration.
Print all items, using a while loop to go through all the index numbers:
thislist = ["apple", "banana", "cherry"] i = 0 while i < len(thislist): print(thislist[i]) i = i + 1
Looping Using List Comprehension
List Comprehension offers the shortest syntax for looping through lists:
A short hand for loop that will print all items in a list:
thislist = ["apple", "banana", "cherry"] [print(x) for x in thislist]
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Example: 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:
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 only accepts the items that valuate to True.
Only accept items that are not "apple":
newlist = [x for x in fruits if x != "apple"]
The condition if x != "apple" will return True 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:
newlist = [x for x in fruits]
Iterable
The iterable can be any iterable object, like a list, tuple, set etc.
You can use the range() function to create an iterable:
newlist = [x for x in range(10)]
Same example, but with a condition:
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:
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:
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:
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 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:
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:
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:
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().