0

I have list l = [1,3,4,5,7,6,4,5,10,1], and i want to fetch elements in position 4, 8. I am using command l[4,8] to fetch both elements, but it's not working. Is it not right method?

  • See this post: [python - Access multiple elements of list knowing their index](https://stackoverflow.com/questions/18272160/access-multiple-elements-of-list-knowing-their-index) – MrCodingB Jan 09 '21 at 10:11

3 Answers3

2
>>> l = [1,3,4,5,7,6,4,5,10,1]
>>> a,b = l[4], l[8]
>>> a,b
(7, 10)
>>> a
7
>>> b
10
>>>
user70
  • 597
  • 2
  • 7
  • 24
0

You could go for something like this:

l = [1,3,4,5,7,6,4,5,10,1]
out = list((l[2], l[4], l[8]))
print(out)

Output:

[4, 7, 10]
solid.py
  • 2,782
  • 5
  • 23
  • 30
0

About Lists

When accessing a list you give it an index i and it returns the i'th element:

>>> x = [0,1,2,3,4,5,6,7]
>>> print(x[3])
3

Notice how when accessing the element "3" it will actually give the fourth element of the list. This is because counting array positions (lists in python) starts at zero in almost every programming language. (f*** Lua)

Python has two extra features with lists not typically found in other languages.

The first is negative overroll where when you give the list a negative index it will count from the back of the list:

>>> print(x[-1])
7

The second is native list slicing, where you can give the list two numbers and it will return a subset of elements in between these two indices:

>>> print(x[1:3])
[1, 2]
>>> print(x[3:-2])
[3, 4, 5]

To your specific problem:

As mentioned by other users, you can access the two elements separately by separating them with a comma:

>>> L = [1,3,4,5,7,6,4,5,10,1]
>>> out = L[4], L[8]
>>> print(out)
(7, 10)

Out is a tuple, which is basically a list you can't write to. You can separate the variables from a tuple (or a list) into separate variables by separating those with a comma on the left side of a definition:

>>> a, b = out
>>> print(a)
7
>>> print(b)
10

If you need to do this very often, here's a function that takes in a list of values and a list of indices, creates a new list and copies all given values into the new list:

def get_from_list(values: list, indices: list):
    out = list()

    for i in indices:
        out.append(values[i])

    return out

a, b = get_from_list(L, [4, 8])

I'm pretty sure that this is a terrible solution performance wise but the code is pretty readable, which I think is good enough for a learners context.

PixelRayn
  • 392
  • 2
  • 13