Python: access list value by reference - python

Very basic question here (I've just started with Python).
I have a list object. It contains five numbers [3,6,2,3,1]
I want find the sum of the first, third and fourth numbers in the list.
What is the syntax?

You can for instance sum elements #1, #3, and #4 with the flexible expression
sum(my_list[i] for i in (0, 2, 3))
The index of the first element is 0 [not 1], etc., i.e. my_list[0] is the first element (with value 3, in the original question), etc.

The items of a list are numbered like this:
a = [3, 6, 2, 3, 1]
^ ^ ^ ^ ^
index 0 1 2 3 4
To access the item with the index i, use a[i]. From here, you should be able to figure out how to sum the desired items.

Just write the index in brackets. Note that the index starts with zero:
lst[0] + lst[2] + lst[3]
In some cases, you can use the sum function and select a slice of the list. For example, to get the sum of the first, third, and fifth element, use:
sum(lst[::2])

You can access an element of a Python list by index by appending [list_index] to the list object (replace list_index with the index you want). For example:
my_list_object = [3,6,2,3,1]
my_sum = my_list_object[0]+my_list_object[2]+my_list_object[3]

Related

Last value not showing up after slicing list

Av = [32,5,3,1,3,4,5]
A = Av[0:int(len(Av)/2)]
B = Av[int(len(Av)/2):-1]
print(A,B)
When I run this block of code, I get
[32, 5, 3] [1, 3, 4]
The last value of Av is 5. But it is not showing up on the list B..
It's because you have sliced the list till -1 which means the last element of the array and is excluded from the sliced array.
To get an array sliced till the end leave the end part of the slice code empty. Like this -
B = Av[int(len(Av)/2):]
In python when you use index slicing Av[a:b] you get the elements from position a (included) to position b (excluded). Because -1 refers to the last position, if you do Av[a:-1], the last element won't be included.
If you want to include the last element, just omit the final index -1, that is use Av[a:]. Your code should be like this:
Av = [32,5,3,1,3,4,5]
A = Av[0:int(len(Av)/2)]
B = Av[int(len(Av)/2):]
print(A,B)
Take a look at https://stackoverflow.com/a/509295/7558835 answer. It explains very clearly how does index slicing work.
When you use the slice [x:-1], it doesn't include the value at index -1 (last position), because it is non-inclusive.
Instead, use [x:], which will give a slice that includes x and all values to its right:
B = Av[int(len(Av)/2):]
Output:
>>>B
>>>[1, 3, 4, 5]

Negative index on nested list

Let's say I've got a nested list like this:
mylist = [[],[],[]]
and I want to insert elements at the end of the second nested list:
mylist[1].insert(-1, 1)
mylist[1].insert(-1, 2)
The output i expected was:
[[], [1, 2], []]
but instead I got:
[[], [2, 1], []]
Can somebody explain this to me? I thought the index -1 always pointed to the last position of a list.
according to documentation (https://docs.python.org/3/tutorial/datastructures.html#more-on-lists), the first argument of the insert method is the index of the element before which to insert...and -1 designates the last element of a list: so by calling insert(-1,...) the element you insert will always become the next to last element of your list.
this is easy to veryfy. if you insert yet another element
mylist[1].insert(-1, 3)
you will notice the resulting list becomes
[[], [2, 3, 1], []]
so should probably use append instead. or calculate the index dynamically like
mylist[1].insert(len(mylist[1]), 3)
If a list has for example 3 elements, they are numbered from 0 to 2 (i.e. 0, 1, 2).
If you want use negative indices, they are numbered from -3 to -1 (i.e. -3, -2, -1).
Now, if you want insert a new element at position -1, it is the same, as inserting at position 2, i.e. the inserted element will become element[2].
But element[2] will be then an element of the 4-element list, so its current position in the negative notation is not -1 but -2:
element[-4], element[-3], element[-2], element[-1]
From this page,
list.insert(index, element) means you insert element at index index. .insert(-1, value) means inserting value at the last element of the list (index=len(lst)-1). So
mylist[1].insert(1, 1)
mylist[1].insert(1, 2)
should solve the problem.
Another approach is to use append as the other one said.
mylist[1].append(1)
mylist[1].append(2)

This Python function removes an unexpected value from the list, not at the index position expected - nested index?

I'm doing a course of study and this is part of a question in one of the modules. It asks for the expected result.
list = [x * x for x in range(5)]
def fun(lst):
del lst[lst[2]]
return lst
print(fun(list))
I have been on to pythontutor.com to see what the code is doing and something odd happens, I'm certain it is due to the line:
del lst[lst[2]]
the first line (list comprehension) creates the list containing [0, 1, 4, 9, 16], then the functions deletes lst[lst[2]], which removes value 16 from the list at index 4. I expected it to remove the value 4 at index 2.
If I change the line to:
del lst[2]
this does remove the value 4 at index 2, so I suppose what I need to understand is what is happening when the line has the list 'nested' ( del lst[lst[2] ) as in the original code. I don't get why it removes the 16 in that case.
I mean you have written this code del lst[lst[2]]. Lets just focus on the lst[2] which is inside of lst[...]. Here, lst[2] is asking for the second index of lst then the second index of lst is 4 as the for loop created. then the lst[2] inside lst[...] becomes 4.
So, at the end it becomes like this:
lst[4] # As the lst[2] is 4 which is generated through loop
So, at the end it removes the 16 which is ate the index no. 4.
Hopefully, you understood.
Let me explain you:
You wrote this code:
del lst[lst[2]]
So, let me go to step by step.
There you wrote lst[2] inside lst[]. the index of lst at 2 is 4 so it means like this if we shorten:
lst[4]
So, it was removing 16 from list which is at index 4
Your lst is
[0, 1, 4, 9, 16]
^ ^ ^ ^ ^
0 1 2 3 4 <--indexes
Hopefully you can see that lst[2] is equal to 4, so
del lst[lst[2]]
is equivalent to
del lst[4]
which removes the element at index 4 (which is the 16).

How to take x many items to the left of a particular index from a list, including 0 many items

Say I have a list
listt = [0,1,2,3,4,5,6,7]
And I want to take 3 items to the left of index 4, I could use this
listt[:4][-3:]
And get
[1, 2, 3]
The general formula is
listt[:index][-places:]
However, this does not work if I want 0 number of items left of 4
listt[:4][-0:]
Gives
[0, 1, 2, 3]
However, I want like to select 0 number of items, so it would be an empty list
[]
So now I am trying to find a general formula which takes 0 number of items into account.
Use listt[index-places:index].
This returns an empty list if 0 <= index < places or places <= 0.
Try this
listt = [0,1,2,3,4,5,6,7]
print(listt[:4][4-3:])
print(listt[:4][4-0:])
The general formula is
listt[:index][index-places:]
You are interpreting this wrongly,
print(listt[:4]) gives you the first 4 elements in the list
print(listt[-3:]) gives you the last 3 elements in the list
That's why when you printed listt[:4][-3:], you are actually printing the last 3 elements of [0, 1, 2, 3] which is [1, 2, 3]
Now, if you print (listt[-0:]), which still equals to printing (listt[:]) & therefore gives you the whole list. Printing listt[:4][-0:] will be like printing the whole list of listt[:4] which gives you back [0, 1, 2, 3]
Therefore, if you want to select none. It's either you select index 0 to 0 which is print(listt[0:0]) or select up to 0 which is print(listt[:0]). Otherwise, you gonna get some values.
Try
listt[k][k-n:k]
Negative index fails in case of zero, but this will do well. However, for n>k this won't work.

Python text for loop list index out of range [duplicate]

This question already has answers here:
How can I iterate over overlapping (current, next) pairs of values from a list?
(12 answers)
Why do I get an IndexError (or TypeError, or just wrong results) from "ar[i]" inside "for i in ar"?
(4 answers)
Closed 6 months ago.
Given the following list
a = [0, 1, 2, 3]
I'd like to create a new list b, which consists of elements for which the current and next value of a are summed. It will contain 1 less element than a.
Like this:
b = [1, 3, 5]
(from 0+1, 1+2, and 2+3)
Here's what I've tried:
b = []
for i in a:
b.append(a[i + 1] + a[i])
The trouble is I keep getting this error:
IndexError: list index out of range
I'm pretty sure it occurs because by the time I get the the last element of a (3), I can't add it to anything because doing so goes outside of the value of it (there is no value after 3 to add). So I need to tell the code to stop at 2 while still referring to 3 for the calculation.
In your for loop, you're iterating through the elements of a list a. But in the body of the loop, you're using those items to index that list, when you actually want indexes.
Imagine if the list a would contain 5 items, a number 100 would be among them and the for loop would reach it. You will essentially attempt to retrieve the 100th element of the list a, which obviously is not there. This will give you an IndexError.
We can fix this issue by iterating over a range of indexes instead:
for i in range(len(a))
and access the a's items like that: a[i]. This won't give any errors.
In the loop's body, you're indexing not only a[i], but also a[i+1]. This is also a place for a potential error. If your list contains 5 items and you're iterating over it like I've shown in the point 1, you'll get an IndexError. Why? Because range(5) is essentially 0 1 2 3 4, so when the loop reaches 4, you will attempt to get the a[5] item. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting the a[5] would mean getting the sixth element which does not exist.
To fix that, you should subtract 1 from len(a) in order to get a range sequence 0 1 2 3. Since you're using an index i+1, you'll still get the last element, but this way you will avoid the error.
There are many different ways to accomplish what you're trying to do here. Some of them are quite elegant and more "pythonic", like list comprehensions:
b = [a[i] + a[i+1] for i in range(len(a) - 1)]
This does the job in only one line.
Reduce the range of the for loop to range(len(a) - 1):
a = [0, 1, 2, 3]
b = []
for i in range(len(a) - 1):
b.append(a[i] + a[i+1])
This can also be written as a list comprehension:
b = [a[i] + a[i+1] for i in range(len(a) - 1)]
When you call for i in a:, you are getting the actual elements, not the indexes. When we reach the last element, that is 3, b.append(a[i+1]-a[i]) looks for a[4], doesn't find one and then fails. Instead, try iterating over the indexes while stopping just short of the last one, like
for i in range(0, len(a)-1): Do something
Your current code won't work yet for the do something part though ;)
You are accessing the list elements and then using them to attempt to index your list. This is not a good idea. You already have an answer showing how you could use indexing to get your sum list, but another option would be to zip the list with a slice of itself such that you can sum the pairs.
b = [i + j for i, j in zip(a, a[1:])]

Categories