mylist = ['12026898019', '12024759878', '12022148703', '12027436222', '12021673017'] for item in mylist: print(item) Answer from steven.daprano on discuss.python.org
🌐
Python.org
discuss.python.org › python help
How can I get a value at any position of a list - Python Help - Discussions on Python.org
October 1, 2022 - I have a numbers added in the list, and want to get a value at a particular number from the list. I tried one = (open(input("Open list: ")).read().splitlines()) list = one print(list) for i in range(len(list)): …
Top answer
1 of 14
1828

As for your first question: "if item is in my_list:" is perfectly fine and should work if item equals one of the elements inside my_list. The item must exactly match an item in the list. For instance, "abc" and "ABC" do not match. Floating point values in particular may suffer from inaccuracy. For instance, 1 - 1/3 != 2/3.

As for your second question: There's actually several possible ways if "finding" things in lists.

Checking if something is inside

This is the use case you describe: Checking whether something is inside a list or not. As you know, you can use the in operator for that:

3 in [1, 2, 3] # => True

Filtering a collection

That is, finding all elements in a sequence that meet a certain condition. You can use list comprehension or generator expressions for that:

matches = [x for x in lst if fulfills_some_condition(x)]
matches = (x for x in lst if x > 6)

The latter will return a generator which you can imagine as a sort of lazy list that will only be built as soon as you iterate through it. By the way, the first one is exactly equivalent to

matches = filter(fulfills_some_condition, lst)

in Python 2. Here you can see higher-order functions at work. In Python 3, filter doesn't return a list, but a generator-like object.

Finding the first occurrence

If you only want the first thing that matches a condition (but you don't know what it is yet), it's fine to use a for loop (possibly using the else clause as well, which is not really well-known). You can also use

next(x for x in lst if ...)

which will return the first match or raise a StopIteration if none is found. Alternatively, you can use

next((x for x in lst if ...), [default value])

Finding the location of an item

For lists, there's also the index method that can sometimes be useful if you want to know where a certain element is in the list:

[1,2,3].index(2) # => 1
[1,2,3].index(4) # => ValueError

However, note that if you have duplicates, .index always returns the lowest index:......

[1,2,3,2].index(2) # => 1

If there are duplicates and you want all the indexes then you can use enumerate() instead:

[i for i,x in enumerate([1,2,3,2]) if x==2] # => [1, 3]
2 of 14
281

If you want to find one element or None use default in next, it won't raise StopIteration if the item was not found in the list:

first_or_default = next((x for x in lst if ...), None)
Discussions

How to get specific values from an element of the list
You can't ever do for i[0]..., that makes no sense. But you don't need a loop here at all. Use index or find to locate the position of "on" in the string, then slice from there: heading = headings[0] pos = heading.find("on") if pos != -1: result = heading[pos+3:] More on reddit.com
🌐 r/learnpython
7
1
December 24, 2021
Get list item by attribute in Python - Stack Overflow
I need to load a list of database row objects into memory, and then grab one of those rows by its unique ID. Is there a clean, pythonic way of finding an single object from a list by an attribute value? More on stackoverflow.com
🌐 stackoverflow.com
Python: get item from list in list - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
Get a key from a dictionary of lists by value of one of list's items
I wouldn't complicate things too much. Iterate over the dictionary, then see if the wanted value is in the list. Something like this: wanted_item = "value2" for key, value in d.items(): if wanted_item in value: print(key) break More on reddit.com
🌐 r/learnpython
9
1
May 1, 2022
🌐
Quora
quora.com › How-do-I-get-a-specific-item-from-a-list-in-Python
How to get a specific item from a list in Python - Quora
From my experience, the easiest ... list in Python is just by using the index in square brackets. For example, if I have a list like my_list = [10, 20, 30] and I want the second item, I just do my_list[1] since indexing starts at 0. It’s straightforward and works every time. ... using an if statement, i pulled values greater than ...
🌐
Reddit
reddit.com › r/learnpython › how to get specific values from an element of the list
r/learnpython on Reddit: How to get specific values from an element of the list
December 24, 2021 -

Hello everyone!

I have a document in Word that I've already parsed.

Here's how headings of that document look like in the list:

['Client Acceptance Screening Report on LTD Western Stream','Analysis of actual or alleged integrity issues','International blacklists, sanctions or other geopolitical concerns','Politically Exposed Persons (PEP)','Corporate details']

How can I get everything from the first element of the list after the word 'on'. I need to get the name of the legal entity which is LTD 'Western Stream'.

I tried this:

scanning = False
    for i[0] in heading:
        if i == 'o' and i+1 == 'n':
        scanning = True
        continue
    if scanning == True:
        print(i)

But it doesn't work.

I also tried this, but it doesn't work either:

scanning = False
for i[0] in heading:
    i[0] = q
    if q == 'o' and q == 'n':
        scanning = True
        continue
    if scanning == True:
        print(q)

I would be very grateful for the help.

🌐
GeeksforGeeks
geeksforgeeks.org › python-accessing-index-and-value-in-list
Accessing index and value in Python list - GeeksforGeeks
May 9, 2025 - The simplest and the most common way to iterate over a list is to use a for loop. This method allows us to access each element in the list directly.Example: Print all elements in the list one by one using for loop.Pythona = [1, 3, 5, 7, 9] # On each
🌐
Linux Hint
linuxhint.com › python_find_element_list
Linux Hint – Linux Hint
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
freeCodeCamp
freecodecamp.org › news › python-find-in-list-how-to-find-the-index-of-an-item-or-element-in-a-list
Python Find in List – How to Find the Index of an Item or Element in a List
February 24, 2022 - You can give a value and find its index and in that way check the position it has within the list. For that, Python's built-in index() method is used as a search tool. ... .index() is the search method which takes three parameters.
Find elsewhere
🌐
Quora
quora.com › How-do-I-access-the-value-of-a-list-in-Python
How to access the value of a list in Python - Quora
Here, the first value, 'Apple', of the list is called by its index position, ‘trees[0]’. ... Python is a versatile programming language that can be used for a variety of applications, from web development and machine learning to data analysis. Python is an especially good choice if you want to get started quickly with coding and don’t need to worry about making your code as efficient as possible. ... 1) Create the list using list_name = [item1...
🌐
W3Schools
w3schools.com › python › python_lists_access.asp
Python - Access List Items
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... Note: The first item has index 0. ... You can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new list with the specified items.
🌐
AskPython
askpython.com › home › 5 easy ways to extract elements from a python list
5 Easy Ways To Extract Elements From A Python List - AskPython
December 29, 2021 - Let’s learn the different ways to extract elements from a Python list When more than one item is required to be stored in a single variable in Python, we need to use lists. It is one of python’s built-in data functions. It is created by using [ ] brackets while initializing a variable.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-get-specific-elements-from-list-in-python
How to get specific elements from list in python - GeeksforGeeks
July 23, 2025 - operator.itemgetter function gives better performance as compared to For Loop or comprehension. It can take multiple indices at once and return a tuple. ... To get the elements based on some condition, you can use List comprehension and filter() method...
🌐
Sentry
sentry.io › sentry answers › python › find item in list in python
Find item in list in Python | Sentry
2 weeks ago - The list comprehension in odd_numbers ... divided by two). If we want only the first item from our list that satisfies our condition, we change our list comprehension into a call to the Python next function. my_list = [1, 4, 7, 8, 3] odd_number = next(n for n in my_list if n%2) print(odd_number) # will print 1 · If next does not find a value, it will throw ...
🌐
Tutorialspoint
tutorialspoint.com › python › python_lists.htm
Python - Lists
A list may have same item at more than one index positions. To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index.
🌐
Reddit
reddit.com › r/learnpython › get a key from a dictionary of lists by value of one of list's items
r/learnpython on Reddit: Get a key from a dictionary of lists by value of one of list's items
May 1, 2022 -

The title's confusing, but hear me out. I have a dictionary set up like this:

{
    "key1": ["value1", "value2"],
    "key2": ["value3", "value4"],
    etc.
}

Is there a way to retrieve a specific key by specifying only a single value from its associated list, i.e. get "key1" by specifying just "value2"? Every single key and value in the entire structure is unique.

So far, I've found this Stack Overflow article which explains how to look up keys by value:

mydict = {'george': 16, 'amber': 19}
print(list(mydict.keys())[list(mydict.values()).index(16)])
# Prints george

...But it only works with flat dictionaries where values are just strings, not lists like in my case. I also could write a function that creates a new dictionary from the original one by manually iterating over it and skipping the unneeded values:

def invertDict(self, dict):
    newDict = {}
    for key, val in dict:
        newVal = str(val[1])
        newDict[newVal] = key
    return newDict

I also could just manually declare a dictionary where keys and values are reversed:

{
    "value2": "key1",
    "value4": "key2",
    etc.
}

But I only need to look it up once in the entire project, and it feels like defining a new dictionary, let alone a new function, just for one line is wasteful. There must be an elegant, pythonic way of doing this in one line, like it often is with Python, but so far I couldn't think of one. Any suggestions?

Top answer
1 of 2
2
I wouldn't complicate things too much. Iterate over the dictionary, then see if the wanted value is in the list. Something like this: wanted_item = "value2" for key, value in d.items(): if wanted_item in value: print(key) break
2 of 2
2
Is there a way to retrieve a specific key by specifying only a single value from its associated list, i.e. get "key1" by specifying just "value2"? Every single key and value in the entire structure is unique. Stop worrying about finding some specific Python solution and first solve the problem yourself. How would you do this if I gave you a printed dictionary? If I said: "tell me the key that has the item 'item1'", how would you go about it? Pretend you're having to explain this to a kindergartener who has never heard of Python, or seven-eggs-short-of-a-dozen Steve from work who browses Facebook all day instead of getting anything done? Now write those steps down. Convert those to comments. Now translate them to Python. For each key:value pair in the haystack search in the value list for the needle If the needle exists, return the key You are confusing yourself by looking at the forest instead of the trees. You don't need to solve "search a dictionary of lists for a value that might be in one of the lists and if so return the key associated with that list", you just need to solve "loop through a dictionary", "search a list", "execute and if-statement", and "return a value". Also, forget you ever saw that SO article and never, ever, ever write code like that.
🌐
StrataScratch
stratascratch.com › blog › how-to-get-the-index-of-an-item-in-a-list-in-python
How to Get the Index of an Item in a List in Python - StrataScratch
September 6, 2024 - This is a common data-cleaning scenario because we expect survey responses to have duplicates (but different responses recorded once). In repeated measures studies, there will be duplicate measurements. The index() function in Python returns only ...