Skip to content

Instantly share code, notes, and snippets.

@islandjoe
Created June 13, 2021 05:48
Show Gist options
  • Save islandjoe/f8241e378a5b6f3d53552818f69cac41 to your computer and use it in GitHub Desktop.
Save islandjoe/f8241e378a5b6f3d53552818f69cac41 to your computer and use it in GitHub Desktop.
Python iterable exercises: Get the length of each string elements in a list.
animals = ['Squirrel', 'Alligator', 'Shark', 'Panther', 'Donkey', 'Gnu', 'Echidna', 'Lark', 'Hornet', 'Dove', 'Dog', 'Sea lion']
## for-loop
animals_ = []
for animal in animals:
animals_.append(len(animal))
animals_
=> [8, 9, 5, 7, 6, 3, 7, 4, 6, 4, 3, 8]
## list comprehension
animals_ = [len(animal) for animal in animals]
animals_
## map
animals_ = map(len, animals)
list(animals_)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment