Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (Retired) Shopping List Lists

lenghth

find the length of the list below

([1, 2, 3])

3 Answers

Matthew Rigdon
Matthew Rigdon
8,223 Points

The simplest way would be to ask Python what the length of that list is using the list command.

my_list = [1, 2, 3]
print(len(my_list))

This will set your list to the variable my_list, then it will simply print out the length of your list, which is 3.

Ryan Ruscett
Ryan Ruscett
23,309 Points

Hey,

Here is how I would do it.

For example:

# Example 1 ok but not great!
my_list = [1,2,3]
x = 0
for y in my_list:
  x += x

#OR

# Example 2 is much better

my_list = [1,2,3]
x = len(my_list)

If I print or return x. If I do that, I see that it's 3. Which is the number of items in my list.

Does this help answer your quesiton? Let me know by liking the answer or if not, than let me know why and I can see what I can do. Thanks!

Use the len() function You can search for len here: https://docs.python.org/2/library/functions.html#len

At the command line, you can just try len([1,2,3]) and it should return 3.