Tobitor
Tobitor

Reputation: 1508

How to get a list with the length of elements of another list?

I have a list with some elements.

l = ['df33g', 'a2', '7661gs', '14153265', 'a5']

Now, I want to get a new list with the length of this elements.

length_elements = [5, 2, 6, 8, 2]

How do we get this?

I wrote this function:

def length_element(element):
  for element in l:
      return len(element)

But it does not work... It returns the length of the first element for each element.

Upvotes: 0

Views: 1714

Answers (4)

Gabio
Gabio

Reputation: 9504

You can use map, which returns an iterator of the results after applying the given function (len in your case) to each item.

If you want to get a list, you can convert it to list using list func:

length_elements = list(map(len, l))

Upvotes: 1

jfaccioni
jfaccioni

Reputation: 7539

A simple list comprehension does this:

l = ['df33g', 'a2', '7661gs', '14153265', 'a5']
length_elements = [len(e) for e in l]

The issue with your function is that you're confusing the variable that you pass in to it with the variable iterated over in the for loop. For learning purposes, this would be a way to fix it:

def length_of_elements(initial_list):
    length_list = [] 
    for element in initial_list:
        length_list.append(len(element))
    return length_list

l = ['df33g', 'a2', '7661gs', '14153265', 'a5']
length_elements = length_of_elements(l)

Upvotes: 3

Stef
Stef

Reputation: 30679

You can map len to the list:

list(map(len,l))

Upvotes: 1

snatchysquid
snatchysquid

Reputation: 1352

Try this:

x = [len(item) for item in l]

This code does exactly what you asked for and is the pythonic short way for saying

x = []
for item in l:
    x.append(len(item))

Upvotes: 3

Related Questions