M03 - Lists Flashcards
List definition and what can be in a list
- Array that contains multiple data items
- Can be data types such as integers, floating-point decimals, strings, and Boolean values as well as lists, tuples, and dictionaries
3 Properties of List
- We can use indexing and slicing to retrieve specific items from the list
- We can add or remove items from a list, which makes lists dynamic data structure
- We can change the contents in a list. This means lists are mutable: we can change one or more items in a list to something else.
List Syntax
list_variable = [‘Item1’ , ‘Item2’ , ‘Item3’ , ‘Etc….’]
Empty List Syntax
empty_list = [ ]
empty_list = list( )
3 general rules for indexing
- Each item in a list has an index that specifies its position in the list
- Indexing starts at 0. Therefore, the index of the first item is 0, second is 1, third is 2, etc.
- Because indexing begins at 0, the index of the last item in a list is 1 less than the total number of items in the list
Get FIRST indexed item from a list syntax
list_variable[0]
Negative Index def + syntax to get LAST item
-Used to identify list item’s position relative to the end of a list
list_variable[-1]
Length of a list syntax
len(list_variable)
Slicing Format and explanation
list_variable[start : end]
- start is the first index item in slice
- end is index marking end of slice
- expression returns list containing from start UP TO BUT NOT INCLUDING end index value
Slice to get index item 3 until the end
list_variable[2:]
Slice to get item 5 until the front
list_variable[: 5]
^have to start 1 AFTER whatever you want
Add items to a list options
append( )
insert( )
append( ) Syntax + where item goes
list_variable.append(‘New Item’)
Goes to end (highest index) of the list
insert( ) Syntax + where item goes
list_variable.insert(index , “New Item”)
Goes to designated position in index
Discard items from a list options
remove( )
pop( )