A List represents a numbered, ordered collection of items. A List may contain zero or more items. A list can contain items of any datatype, but as a best practice, all items in a list should share a datatype and structure:
# DO:[][1,2,3,4][100,75,33]["fun","times","right?"][{"a":1,"b":2},{"a":5,"b":6}] # lists can contain dictionaries[[1,2,3], [4,5,6], [7,8,9]] # lists can be "nested" inside other lists# DON'T:[100,"fun"] # mixed datatypes[{"a":1,"b":2},{"x":5,"z":6}] # non-standard dictionary keys
Like other languages, individual list items can be accessed by their index. List item indices are zero-based, meaning the index of the first list item is 0.
arr = ["a","b","c","d"]arr[0]#> "a"arr[1]#> "b"arr[2]#> "c"arr[3]#> "d"arr[4]#> IndexError: list index out of rangearr.index("a")#> 0arr.index("b")#> 1arr.index("c")#> 2arr.index("z")#> -1 (applies to any item not found in the list)
Remove duplicate values in a list by converting it to another datatype called a "Set" (which rejects non-unique values), and then converting it back to a "List":
A list can be iterated, or "looped" using a for ... in ... statement:
for letter in ["a","b","c","d"]:print(letter)#> a#> b#> c#> d
TIP: If it helps, you can vocalize this like "for each item in the list of items, do something with that item"
A common pattern is to loop through one list to populate the contents of another:
arr = [1,2,3,4]arr2 = []for i in arr: arr2.append(i *100)arr #> [1, 2, 3, 4]arr2 #> [100, 200, 300, 400]
Mapping
Lists can be looped "in-place" using Python's built-in map() function. The map() function takes two parameters. The first parameter is the name of a pre-defined function to perform on each item in the list. The function should accept a single parameter representing a single list item. The second parameter is the actual list to be operated on:
arr = [1,2,3,4]defenlarge(num):return num *100arr2 =map(enlarge, arr)arr2 #> <map object at 0x10c62e710>list(arr2)#> [100, 200, 300, 400]
NOTE: remember to use the return keyword in your mapping function!
Another way of mapping is to use a list comprehension:
arr = [1,2,3,4][i *100for i in arr] #> [100, 200, 300, 400]teams = [{"city":"New York","name":"Yankees"},{"city":"New York","name":"Mets"},{"city":"Boston","name":"Red Sox"},{"city":"New Haven","name":"Ravens"}][team["name"]for team in teams] #> ['Yankees', 'Mets', 'Red Sox', 'Ravens']
Use the filter() function to select a subset of items from a list - only those items matching a given condition. The filter function accepts the same parameters as the map() fuction:
arr = [1,2,4,8,16]defall_of_them(i):returnTrue# same as ... return i == idefequals_two(i):return i ==2defgreater_than_two(i):return i >2defreally_big(i):return i >102filter(all_of_them, arr)#> <filter at 0x103fa71d0>list(filter(all_of_them, arr))#> [1, 2, 4, 8, 16]list(filter(equals_two, arr))#> [2]list(filter(greater_than_two, arr))#> [4, 8, 16]list(filter(really_big, arr))#> []
Note: depending on how many items matched the filter condition, the resulting filtered list may be empty, or it may contain one item, or it may contain multiple items
When using the filter function, observe this alternative filtering syntax involving the keyword lambda:
arr = [1,2,4,8,16]list(filter(lambdai: i >2, arr))#> [4, 8, 16]
If your list is full of dictionaries, you can filter() based on their attribute values:
If you need to implement complex filtering conditions, consider using a list comprehension, or "lambda" syntax, or consider writing out your function the long way:
teams = [{"city":"New York","name":"Yankees"},{"city":"New York","name":"Mets"},{"city":"Boston","name":"Red Sox"},{"city":"New Haven","name":"Ravens"}]# using a list comprehensiondefteams_from(city):return [team for team in teams if team["city"]== city]# using "lambda" syntaxdefteams_from2(city):returnlist(filter(lambdateam: team["city"] == city, teams))# the long waydefteams_from3(city): matches = []for team in teams:if team["city"].upper()== city.upper(): matches.append(team)return matchesprint(teams_from("New York"))#> [{'city': 'New York', 'name': 'Yankees'}, {'city': 'New York', 'name': 'Mets'}]print(teams_from2("New York"))#> [{'city': 'New York', 'name': 'Yankees'}, {'city': 'New York', 'name': 'Mets'}]print(teams_from3("New York"))#> [{'city': 'New York', 'name': 'Yankees'}, {'city': 'New York', 'name': 'Mets'}]