Lists and Dictionaries: Difference between revisions
Appearance
No edit summary |
No edit summary |
||
Line 10: | Line 10: | ||
Access elements | Access elements | ||
<syntaxhighlight lang="python" line> | <syntaxhighlight lang="python" line> | ||
print(animals[0] # first item | print(animals[0]) # first item | ||
print(animals[-1] # last item | print(animals[-1]) # last item | ||
print(animals[-2] # penultimate item | print(animals[-2]) # penultimate item | ||
print(f"{animals[0].title()} is a cow.") # in an f-string | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Modify, add, insert elements | |||
<syntaxhighlight lang="python" line> | <syntaxhighlight lang="python" line> | ||
animals[3] = 'veau' # replace item 3 | |||
animals.append('croc') # add new item to end of list | |||
animals.insert(1,'pato') # insert item at index 1 | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Remove elements | |||
<syntaxhighlight lang="python" line> | <syntaxhighlight lang="python" line> | ||
del animals[0] # delete item at index 0 | |||
popped_animal = animals.pop() # remove last item | |||
popped_animal = animals.pop(2) # remove item at index 2 | |||
animals.remove('veau') # remove (first instance of) item by value | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Organize Lists | |||
<syntaxhighlight lang="python" line> | |||
animals.sort() # sort values a-z | |||
animals.sort(reverse=True) # sort values z-a | |||
animals.reverse() # reverse order (not z-a) | |||
print(sorted(animals)) # temporarily sort | |||
len(animals) # returns number of items | |||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 10:17, 31 March 2024
Lists
Create a list
people = [] # empty list
animals = ['daisy','pat','wabbit','bunny']
Access elements
print(animals[0]) # first item
print(animals[-1]) # last item
print(animals[-2]) # penultimate item
print(f"{animals[0].title()} is a cow.") # in an f-string
Modify, add, insert elements
animals[3] = 'veau' # replace item 3
animals.append('croc') # add new item to end of list
animals.insert(1,'pato') # insert item at index 1
Remove elements
del animals[0] # delete item at index 0
popped_animal = animals.pop() # remove last item
popped_animal = animals.pop(2) # remove item at index 2
animals.remove('veau') # remove (first instance of) item by value
Organize Lists
animals.sort() # sort values a-z
animals.sort(reverse=True) # sort values z-a
animals.reverse() # reverse order (not z-a)
print(sorted(animals)) # temporarily sort
len(animals) # returns number of items