[Tutor] Is there a better way to write my code?

Rafael Knuth rafael.knuth at gmail.com
Mon Aug 13 11:53:46 EDT 2018


I wrote this code below which aims to concatenate strings with their
respective string length.
I was wondering if there is a shorter, more elegant way to accomplish this task.
Thanks!

animals = ["Dog", "Tiger", "SuperLion", "Cow", "Panda"]

# step one: convert the animal list into a list of lists

animals_lol = []

for animal in animals:
    animal_split = animal.split(",")
    animals_lol.append(animal_split)

# step two: collect the length of each string in a separate list

animals_len = []

for animal in animals:
    animals_len.append(len(animal))

# step three: append the length of each string to the list of lists

for a, b in enumerate(animals_lol):
    b.append(animals_len[a])

print(animals_lol)

[['Dog', 3], ['Tiger', 5], ['SuperLion', 9], ['Cow', 3], ['Panda', 5]]


More information about the Tutor mailing list