Store multiple items using a single variable and build cleaner code for other developers to understand.
Create a list, name it, and assign variables to it using the syntax
list = ['item1','item2','item3']
For example, if you were creating a list of social media platforms named
platforms, you would use:
platforms = ['Facebook','Twitter','Pinterest']
Each item within a list has an index number based on its order within the list, starting from zero. So the first item has an index of 0, the second item has an index of 1, the third item has an index of 2, and so on. For example, to output a single entry in a list of social media platforms:
>>> platforms = ['Facebook','Twitter','Pinterest'] >>> platforms Output: 'Facebook' >>> platforms Output: 'Twitter' >>> platforms Output: 'Pinterest' ```You can also add or delete elements using indexes. ## Add new items to a list by restating the list with the new items included. If you want to add `Reddit` to the `platforms` list, include it in single quotes in your list:
platforms = [‘Facebook’,‘Twitter’,‘Pinterest’,‘Reddit’]
## Use a programmatic expression to delete a value from the list with the syntax `del list[index]`. For example, if you no longer need `Pinterest` on your list, and it has an index number of 2, to delete it:
## Use multi dimensional lists to store a combination of list elements using the syntax `mdlist = [['item1-1','item1-2'],['item2-1','item2-2'],['item3-1','item3-2']]`. For example, if you want to store the number of leads per social media platform, use:
platform_metrics = [[‘Facebook’,125],[‘Twitter’,288],[‘Reddit’,221]]
## Use `len()` to find out how many items are in a list, `max()` to find a list's maximum value, `min()` to find a list's minimum value, and `sorted()` to sort list output alphabetically or numerically. For example:
len(['1','2','3']) output: 3
max(['1','2','3']) output: 3
sorted(['Bill','Sara','Apple']) output: ['Apple','Bill','Sara'] ``` ## Use arithmetic operators like `+` and `-` to perform arithmetic operations using elements in the list. For example, if you want to find the age difference between two people, you can use: ``` Name = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] Age = [22,34,42,27,57] print(Age-Age) ```The returned value would be `34-22 = 12`. If instead you want to add the first and second ages together, you can use: ``` ``` Names = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack'] Age = [22,34,42,27,57] print(Age+Age) ``` ```The returned value would be `22+34 = 56`.