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

Mats Wichmann mats at wichmann.us
Mon Aug 13 16:11:12 EDT 2018


On 08/13/2018 09:53 AM, Rafael Knuth wrote:
> I wrote this code below which aims to concatenate strings with their
> respective string length.

did you mean concatenate? because you don't do any concatenation...

any time you hear keeping a data element with some information
associated, you should be thinking a dictionary data type, though
there's nothing wrong with having a data element be a list or a tuple
either, and we don't know if you have some specific requirements that
are not showing here.

> 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]]

If you want a dictionary, you can try this one-liner:

animalinfo = { animal: len(animal) for animal in animals }
print(animalinfo)



More information about the Tutor mailing list