Access two consecutive elements of a list in Python [duplicate] - python

This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 9 years ago.
I need to access the n and n+1 elements of a list. For example, if my list was [1,2,3,4,5] and my nth element was 2, I'd need the next element in the list, 3.
Specifically, I need to access these elements in order to use them to look up a value in a matrix A
I have a for loop that's iterating over the list:
list = [1,2,3,4,5]
for i in list:
value = A[i,i+1] #access A[1,2], A[2,3], A[3,4], A[4,5]
the problem with this is that I can't do an i+1 operation to access the n+1 element of my list. This is my first time programming in Python and I assumed element access would be the same as in C/C++ but it's not. Any help would be appreciated.

You can use slicing operator like this
A = [1, 2, 3, 4, 5]
for i in range(len(A) - 1):
value = A[i:i+2]
The range function lets you iterate len(A) - 1 times.

Enumerate can give you access to the index of each item:
for i, _ in enumerate(A[:-1]):
value = A[i:i+2]
If all you need are the pairs of data:
for value in zip(A, A[1:]):
value

Related

Remove duplicate of a list via list matching in Python [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Removing duplicates in lists
(56 answers)
Closed 7 days ago.
I have chosen a slightly different procedure to remove duplicates of a list. I want to keep a new list in parallel, in which each duplicate is added. Afterwards I check if the element is present in the "newly created list" in order to delete it.
The code looks like this:
# nums = [1,1,2] or [0,0,1,1,1,2,2,3,3,4]
t = []
nums_new = nums
for i in nums:
if nums[i] not in t:
t.append(nums[i])
else:
nums_new.remove(nums[i])
nums = nums_new
print(nums)
For the case when nums = [1,1,2] this works fine and returns [1,2].
However, for nums = [0,0,1,1,1,2,2,3,3,4] this case does not seem to work as I get the following output: [0, 1, 2, 2, 3, 3, 4].
Why is this? Can someone explain me the steps?
There are two issues with your code:
Since you are iterating over a list, for i in nums, i is your actual number, not the indexer, so you should just use i instead of nums[i].
nums_new = nums will not actually make a copy of nums, but instead it will make a second binding to the very same list. So you should write nums_new = nums.copy() to avoid changing your original list while you iterate over it.
With those two changes your code works as you wish:
nums = [0,0,1,1,1,2,2,3,3,4]
t = []
nums_new = nums.copy()
for i in nums:
if i not in t:
t.append(i)
else:
nums_new.remove(i)
nums = nums_new
print(nums)
Returns [0,1,2,3,4].
Of course this is an academic exercise of some kind, but note that the Pythonic way to remove duplicates from a list is:
list(dict.fromkeys(nums)) if you want to preserve the order, and
list(set(nums)) for a slightly faster method if you do not care about order.

Is there a brief way to Get the indices of all elements from list A in list B [duplicate]

This question already has answers here:
Find indexes of common items in two python lists
(3 answers)
Closed 1 year ago.
Assume we have two lists, A and B. Is there a way to get the indices of elements in the list B, which are in the list A?
For example:
A = [1,2,3,4]
B = [3,4,1,2,5]
The result should be:
[2,3,0,1]
Could it be implemented without for-loop (or fast)?
This should work for your use case:
result = [A.index(x) for x in B if x in A]
Use index function
A = [1,2,3,4]
B = [3,4,1,2,5]
lst=[]
for i in A:
res=B.index(i)
lst.append(res)
print(lst)
# [2, 3, 0, 1]

Remove specific consecutive duplicate in a list [duplicate]

This question already has answers here:
Remove certain consecutive duplicates in list
(6 answers)
Closed 2 years ago.
The post is similar to this but what I want, is to remove specific consecutive duplicate in a list.
So let's say we have this list:
[1,1,1,2,2,3,2,4,4,4,1]
I want to have:
[1,2,2,3,2,4,4,4,1]
I want to remove only the "ones". I am trying itertools.groupby but I haven't found a way to do it.
You could use itertools.groupby and use the grouping key to either keep the key or keep the returned group:
l = [1,1,1,2,2,3,2,4,4,4,1]
from itertools import chain, groupby
list(chain.from_iterable([k] if k==1 else v for k,v in groupby(l)))
# [1, 2, 2, 3, 2, 4, 4, 4, 1]
If you search for ones at the beginning of the list, you do not need to import a module to do this, it is also possible to iterate over the elements in a for-loop:
your_list = [1,1,1,2,2,3,2,4,4,4,1]
for index, element in enumerate(your_list):
if element != 1:
break
if index:
result = your_list[index-1:]
else:
result = your_list
This would check for ones, until it finds another number. The index of the other number -1 is meant to be the beginning of the list.
If there is no 1 in the list, index will be zero and the original list is returned.

How to get sum of all elements of given list using list comprehension? [duplicate]

This question already has answers here:
How to emulate sum() using a list comprehension?
(10 answers)
Closed 4 years ago.
l = [5, 7, 8, 2, 1, 4]
sum = 0
for i in l:
sum += i
print(sum)
how can I get sum of all elements but using list comprehension?
list comprehension should be used only for generating a list. You can simply use sum(l).
List comprehension always produces another list so I am not sure if you can even do that. You will surely need other function to fold the sequence into a single value.

Delete multiple values in a list of python [duplicate]

This question already has answers here:
Deleting multiple elements from a list
(32 answers)
Closed 7 years ago.
I have an index of list elements that I want to delete. How can I do that ?
For example, if my original list is a=[1,2,3,4,5,6] and my index list is [2,3]. I want the elements 3,4 to be removed
Since you want to delete the indices, you can do the following two methods:
In place:
for index in sorted(indices, reversed=True):
del a[index]
out of place:
new_a = [el for index, el in enumerate(a) if index not in indices]
The reason why we sort for the in-place version is because deleting from the back doesn't modify the referenced elements in the front (note that this breaks with negative indexing).
a=[1,2,3,4,5,6]
a = a[:2] + a[4:]
print(a)
[1, 2, 5, 6]

Categories

Resources