So I have been given lst = [1001, 21, 1, 404, 200, 12010], and when I run the program I need to print out only the 3 and 4 digits : [1001, 400, 200].
>>> lst = [1001, 21, 1, 404, 200, 12010, 2002]
>>> str_lst = str(lst)
>>> new_lst = [len(number) for number in str_lst]
>>> print(new_lst)
and the result of this code is [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
I've tried this after your comment :
new_lst = [len(str(number)) for number in lst]
print(new_lst)
for number in new_lst == 3 and number in new_lst == 4:
final_result.append(number)
print(final_result)
When you write str_lst = str(lst)
, it converts this [1001, 21, 1, 404, 200, 12010, 2002]
to one whole string. Thus when you'll print your str_list
you'll get an output like this - '[1001, 21, 1, 404, 200, 12010, 2002]'
, which is one string literal.
print(str_lst[0])
[
print(str_lst[1])
1
What you need is to convert every individual element of your original list to string. Which can be achieved like:
new_lst = [len(str(number)) for number in lst]
The output of the above code will be:
print(new_lst)
[4, 2, 1, 3, 3, 5, 4]
This way you can get a list whose elements are the length of the elements of the original list.
Just a suggestion: While debugging small problems, try printing out values after every operation. This why you can compare the output with your expectations. Not only this will help you get a solution, you'll also learn Python in much more depth.
Edited after comments:
final_result = []
for count, i in enumerate(new_lst):
if i >= 3:
final_result.append(lst[count])
print(final_result)