How can I print more than one item in a list using one code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How can I print more than one item in a list using one code?

my_list = [3, 4, 5, 6, "hg"] print (my_list[0]) >>>this will print "3" i think. but I want to print 3, 6 or others using one line only<<<

20th Aug 2017, 8:11 AM
Mohamed Akl
Mohamed Akl - avatar
1 Answer
0
It really depends what you want to grab from the list, how technical you wanna get, and what you mean by "one code". There are several approaches I can give you. If you don't understand most of them, I would suggest the slicing option: 1. print everything using a comprehension: my_list = [3, 4, 5, 6, "hg"] [print(each) for each in my_list] 2. Slicing - you can choose which index to start grabbing elements, and where it ends: my_list = [3, 4, 5, 6, "hg"] print (my_list[:]) 3. format method - it's a function that works with strings and allows you to place a given argument to format inside the string anywhere with {} my_list = [3, 4, 5, 6, "hg"] for i in range(len(my_list)): print("{}".format(my_list[i])) 4. index method for list - basically a function that asks the list if 3 or 6 exists, if so, return them. Keep in mind, if the number you index does not exist, you'll get an error: my_list = [3, 4, 5, 6, "hg"] print (my_list.index(3), my_list.index(6))
20th Aug 2017, 11:35 AM
Sapphire