I have a variable that retrieves a list of items that could be 1 or more but when I have only 1 and I try to print it I get every single character printed individually for example, let say that my list only has this:
list = ['apple']
for x in list:
print(x)
when i run it i get this:
a
p
p
l
e
but if i have something like this:
list = ['apple', 'lemon']
for x in list:
print(x)
and i run it, I get it printed correctly like this:
apple
lemon
and when i use the len function to check the item content i get the total character for the one single item, like in apple if i do this:
list = 'apple'
print(len(list))
i get this:
5
but if i get more than one value inside the list i get the total items inside the lists like this:
list = ['apple', 'lemon']
print(len(list))
and i run it i get:
2
so my question is, how can i solve this problem?
CodePudding user response:
In the first case you used list
as a variable name for the string apple
. The length of this string is 5.
In the second case you used list
as a variable name for the list ['apple', 'lemon']
. The length of this list is 2.
CodePudding user response:
When you have 1 and only 1 element you're using a string instead of a list. list = 'apple'
should be list = ['apple']
Both lists and strings and lists can be iterated over.
When you iterate over a list of strings and print out every element you're printing out strings.
for s in ['abc', 'def', 'ghi']:
print(s)
When you iterate over a string and print every element you're printing out every character.
for c in 'abcdefg'
print(c)
In your investigation when looking at the length you're looking at the length of a string instead of a list. You can validate this by checking the type of the variable.
# This isn't actually a list
list = 'apple'
print(len(list))
# 5
print(type(list))
# <class 'string'>
If you place the string within a list you will get the behavior you expect.
list = ['apple']
print(len(list))
# 5
print(type(list))
# <class 'list'>