In my recent Python adventures I've ended up having to slice, dice and manage lists and I've learned a lot on that journey.

Here's a cheat sheet with some nifty lists methods, that will hopefully help you on your Python journey:

Slicing Lists 🍰

main_characters = ["Harry Potter", "Lord Voldemort", "Albus Dumbledore", "Hagrid", "Ron Weasley"]

# get all of items from Voldermort to beginning of the list
# notice how it starts from an index that's one more then the actual 
# Voldemorts index

main_characters[:2]
# => ["Harry Potter", "Lord Voldemort"]

# get all of the items from Albus to the end of the list
# notice how 2 is the actual index of Albus

main_characters[2:]
# => ["Albus Dumbledore", "Hagrid", "Ron Weasley"]

years_of_experience = [1,2,3,4,5,6,7,8,9,10]

# get all of the items year 3 and year 7 (including year 3 and 7)

years_of_experience[2:7]
# => [3,4,5,6,7]

Counting Things In Lists πŸ€“

import collections
years_of_experience = [1,2,3,4,4,4,5,6,7,8,9,10,4,2,2,2,4]

# count how many times number 4 showed up in a list

years_of_experience.count(4)
# => 5

# or

collections.Counter(years_of_experience).get(4)
# => 5

# count occurance of all items in a list

collections.Counter(years_of_experience)
# => Counter({4: 5, 2: 4, 1: 1, 3: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1})

Removing Things In Lists πŸ”ͺ

# removing an item from a list 
years_of_experience = [1,2,3,4,4,4,5,6,7,8,9,10,4,2,2,2,4]

# remove number 10 from a list 
years_of_experience.remove(10) # mutates the list

# remove an item with index 1 from the array
del(years_of_experience[1]) # mutates the list

# remove duplicates from lists
sorted(set(years_of_experience)) # sorted returns copy of the list
# => [1, 2, 3, 4, 5, 6, 7, 8, 9]

That'd be all folks!

Auf Wiedersehen πŸ‘‹