I am trying to print multiple items from a list in Python. I have looked at many examples but I am unable to get them to work. What is a good way to print items from the imported list based on their list index.
The commented out example in my code is what I thought will work and cant find a simple solution.
items = []
with open('input.txt') as input_file:
for line in input_file:
items.append(line)
print(items[5],items[6])
#print(items[5,6,7]
One way to do it would be with a for loop.
item_list = ['a','b','c','d','e','f','g','i'] # an example list.
index_to_print = [5,6,7] # add all index you want to print to this list.
for i in item_list:
if item_list.index(i) in index_to_print:
print(i)
update: instead of looping through the whole item_list, we can loop through the indexes you want to print.
for i in index_to_print:
if i < len(item_list):
print(item_list[i])
else:
print('given index is out of range.')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.