How can I get a value at any position of a list

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)):
  print(list.index(i))

And I’m getting error

['12026898019', '12024759878', '12022148703', '12027436222', '12021673017']
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 12, in <module>
ValueError: 0 is not in list

Short answer: [i].

list.index(i) will search a list for an entry matching i and tell you at what index it found it.

Other points:

Try not to redefine the names of built-in types/objects like list. It is mostly harmless and Python lets you do it, but it will be confusing later if you need to refer to the type list in the same scope.

There are easier ways to read the lines of a file. You can iterate over the lines of directly (7. Input and Output — Python 3.10.7 documentation), if you just want a single pass, or give the open file to the list() constructor and it will read it all into a list .

Maybe you don’t understand what i really want

This is my list
Example:

Open list: list

['12026898019', '12024759878', '12022148703', '12027436222', '12021673017']

And i want to print them out one by one like this
Example:

12024759878
12022148703
12027436222
12021673017
mylist = ['12026898019', '12024759878', '12022148703', '12027436222', '12021673017']
for item in mylist:
    print(item)
1 Like

One way of doing it: “print items in list separated by newline”:

data = ['12026898019', '12024759878', '12022148703', '12027436222', '12021673017']
print(*data, sep=´"\n")
1 Like

Thanks i got it done now, by using

for x in lst:
    print(x)

You want to read lines from a file into a list and print them. My suggestion is:

with open(input("Open list: ")) as lines:
    # Strip spaces/newline from each line as it is read
    mylist = list(map(str.strip, lines))

for item in mylist:
    print(item)

Note that these will be strings. If you want actual integers, then replace str.strip with int.

And you asked how to retrieve an element from the list at an arbitrary position, and were puzzled that mylist.index(i) doesn’t do that. This should make both clear:

>>> mylist[3]
'12027436222'
>>> mylist.index('12027436222')
3
1 Like