Skip to content
Advertisement

How to select range with input user in list

I want to select a range between elements in a list, but instead of putting, for example, item 7, I put what I’m seeing in elements. The number between ‘document’ and ‘35621’ changes, I need to convert these numbers to a range (I think?)

I don’t really know how to make this.

data_input = raw_input("nEnter range: n")

my_list = ['document-452-35621', 'document-453-35621', 'document-454-35621', 'document-455-35621', 'document-456-35621', 'document-457-35621', 'document-458-35621', 'document-459-35621', 'document-460-35621']

print my_list[5:9] 

For example, in my list I have:

[
    'document-452-35621', 
    'document-453-35621', 
    'document-454-35621', 
    'document-455-35621', 
    'document-456-35621', 
    'document-457-35621', 
    'document-458-35621', 
    'document-459-35621', 
    'document-460-35621'
]

I enter in choice input : 456-460

The result would be:

[
    'document-456-35621',
    'document-457-35621',
    'document-458-35621',
    'document-459-35621',
    'document-460-35621'
]

Advertisement

Answer

You can do it like this:

my_list = [
    'document-452-35621',
    'document-453-35621',
    'document-454-35621',
    'document-455-35621',
    'document-456-35621',
    'document-457-35621',
    'document-458-35621',
    'document-459-35621',
    'document-460-35621'
]

data_input = input("nEnter range: n").split('-') # ['456', '460']
lower_bound = int(data_input[0]) # 456
upper_bound = int(data_input[1]) # 460

new_list = []
for item in my_list:
    if lower_bound <= int(item.split('-')[1]) <= upper_bound:
        new_list.append(item)

print(new_list)

Or alternatively, you can use List Comprehension and do it like this:

new_list = [item for item in my_list if lower_bound <= int(item.split('-')[1]) <= upper_bound]
print(new_list)

Output:

[
    'document-456-35621',
    'document-457-35621',
    'document-458-35621',
    'document-459-35621',
    'document-460-35621'
]

I can see that you’re using Python 2, so the only difference I think is with the print and raw_input. However, since “Python 2.7 will not be maintained past 2020,” I would encourage you to use Python 3 and above.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement