HungoverCoder
HungoverCoder

Reputation: 23

Python - Why is len() always return 1 for list

Not sure why len() is returning just 1 as output in Python. Should be 4.

names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
num_items = len(names)
print(num_items,",",names,type(names))

Output

Give me everybody's names, separated by a comma. angel,barbara,mary,jjjj
1, ['angel,barbara,mary,jjjj'] <class 'list'>

Upvotes: 1

Views: 1189

Answers (4)

Joey
Joey

Reputation: 1

You need to split by "," or separate your input with comma and space.

Upvotes: 0

Tal Folkman
Tal Folkman

Reputation: 2571

the problem with your code is that there isn't a way to split like this ", ". the correct way to do so is by removing the space and split like "," this is the correct code:

names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(",")
num_items = len(names)
print(num_items,",",names,type(names))

Upvotes: 0

Expurple
Expurple

Reputation: 921

In your input string ('angel,barbara,mary,jjjj') names are separated with commas without spaces (','), but you try to split it by comma and space (', '). There is no ', ' in the string, so it's not split

Upvotes: 1

xxSirFartAlotxx
xxSirFartAlotxx

Reputation: 404

You are splitting the input on , . remove the space.

Upvotes: 0

Related Questions