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

Neil Cerutti neilc at norwich.edu
Mon Aug 13 16:26:26 EDT 2018


On 2018-08-13, Rafael Knuth <rafael.knuth at gmail.com> wrote:
> 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"]

You can perform the whole operation with a single list
comprehension.

animals_lol = [[a, len(a)] for a in animals]

Which is shorthand for the following loop:

animals_lol = []
for a in animals:
    animals_lol.append([a, len(a)])

-- 
Neil Cerutti



More information about the Tutor mailing list