This question already has answers here:
How do I get the last element of a list?
(25 answers)
Cycle through list starting at a certain element
(7 answers)
Closed 4 years ago.
list1 = [1,2,3,4]
If I have list1 as shown above, the index of the last value is 3, but is there a way that if I say list1[4], it would become list1[0]?
You can you modulo math like:
Code:
list1 = [1, 2, 3, 4]
print(list1[4 % len(list1)])
Results:
1
In the situation you described, I myself use the method #StephenRauch suggested. But given that you added cycle as a tag, you might want to know there exists such a thing as itertools.cycle.
It returns an iterator for you to loop forever over an iterable in a cyclic manner. I don't know your original problem, but you might find it useful.
import itertools
for i in itertools.cycle([1, 2, 3]):
# Do something
# 1, 2, 3, 1, 2, 3, 1, 2, 3, ...
Be careful with the exit conditions though, you might find yourself in an endless loop.
You could implement your own class that does this.
class CyclicList(list):
def __getitem__(self, index):
index = index % len(self) if isinstance(index, int) else index
return super().__getitem__(index)
cyclic_list = CyclicList([1, 2, 3, 4])
cyclic_list[4] # 1
In particular this will preserve all other behaviours of list such as slicing.
Related
This question already has answers here:
python count duplicate in list
(7 answers)
Closed 1 year ago.
What I have already is a function that returns which numbers are duplicates like this:
X = [1, 1, 1, 2, 2]
def Dupe(l):
return set([x for x in l if l.count(x) > 1])
print(Dupe(X))
which will return {1, 2}.
What I am looking to do is have a function like this:
X = [1, 1, 1, 2, 2]
def DupeL(l):
(CODE HERE)
print(DupeL(X))
and that would return {3, 2} because there are three ones and two twos. Any ideas?
You were going correct. But I would recommend you to create a dict which shows you the element as well as the number of times it is repeated. Iterate the set and check for occurences for each element of set in the list. Just use .count() method to get the number of occurences in the list. Then add it to an empty dict which shows you the element and it's duplicates. Your code:
x=[1,1,1,2,2]
def Dupe(x):
di={}
c=set([v for v in x if x.count(v)>1])
for i in c:
di[i]=x.count(i)
return di
print(Dupe(x))
This question already has answers here:
Remove duplicates from list python
(4 answers)
Closed 4 years ago.
I have learned that I can use the so-called list comprehension to make python 'for loops' shorter if I want to create a list. For example, instead of writing:
b = []
a = [2, 3, 5]
for x in a:
b.append(x**2)
I can write my code like this:
b = [x**2 for x in a]
I was wondering how can I convert the below code to the second shorter format:
lst = [1, 2, 3, 3, 4, 5, 5]
u_lst = []
for x in lst:
if x not in u_lst:
u_lst.append(x)
As #PritoshSingh has pointed out in the comment, a list construction that involves references to items already constructed in the same list is not suitable for the use of a list comprehension, which is best for value mapping and/or filtering based on conditions not involving the list being constructed itself.
The problem you're describing can be best solved by using the dict.from_keys method, which ignores items it has already seen as it reads from the given sequence:
u_list = list(dict.from_keys(lst))
Use collections.OrderedDict in place of dict if you're using Python 3.6 or earlier versions, where order of dict keys is not guaranteed.
From the specific example given it seems like you want u_lst to be a list of unique values only. If so, there is no need for any list comprehensions, just use a set on the original list:
lst = [1, 2, 3, 3, 4, 5, 5]
u_lst = list(set(lst))
Outputs {1, 2, 3, 4, 5} without converting into a list and [1, 2, 3, 4, 5] with it.
Note that using set on a list produces a set, to get it to behave as a list, you would then convert it into a list as above.
This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
How to remove items from a list while iterating?
(25 answers)
Closed 4 years ago.
I'm trying to iterate over a list of number and removing the values that are lower than a number that I use to compare.
My problem is that there's a number that is lower than the value that I use but it doesnt get removed.
I'm using the remove() function of the list but I don't know why it doesn't get removed
Here is my code:
def remove_lower_numbers(array_numbers, bigger_number):
for elem in array_numbers:
if elem <= bigger_number:
array_numbers.remove(elem)
print(array_numbers)
It works if I used a list comprehension like this:
array_numbers = [x for x in array_numbers if x >= bigger_number]
but I want to do it the way I firts mentioned for learning purposes
I call the function like this:
cards_array = [3, 2, 7]
remove_lower_numbers(cards_array, 8)
but the function prints:
[2]
and 2 is lower than 8 it should return None or a empty list.
Using filter, which keeps only the values that return True for the lambda function:
list(filter(lambda x: x > 3, [1, 2, 3, 4, 5, 2, 3]))
Output:
[4, 5]
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 4 years ago.
I'm trying to iterate over a Python list and delete each element once I've done some tasks with it, but it jumps one element after each iteration and I don't know why:
>>> simple_list = list(range(10))
>>> simple_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in simple_list:
... print(i)
... simple_list.remove(i)
...
0
2
4
6
8
>>> simple_list
[1, 3, 5, 7, 9]
Does anyone know why this is happening? Only the even elements are being removed, and looks like the loop doesn't go through the uneven ones.
Well, your list is shrinking while you are iterating over it. If you want to, just look at the first element while your iterate over it.
while len(simple_list) > 0:
print(simple_list[0])
del simple_list[0]
You can use list comprehension to get copy of the array and then iterate.
simple_list = list(range(10))
for i in simple_list[:]:
print(i)
simple_list.remove(i)
Or this:
for i in simple_list[:]:
simple_list.remove(i)
print(simple_list)
Output:
[]
Ok, found the answer here: Python: Removing list element while iterating over list
You should NEVER delete an element from a list while iterating over it in a for loop. You could use a while loop instead. Or, record the indices of all the elements you want to remove and then delete them after the iteration is complete
This question already has answers here:
Efficient way to rotate a list in python
(27 answers)
Closed 9 years ago.
Say you have a list [1,2,3,4]
And I want to get [2,3,4,1] or [3,4,1,2].
Basically I am using the list with a different starting point each time, but then continuing through the list. How would I create something to recognize that in python.
What i have now is list[n:] where n is the shifted value, say 2, making you start at three.
someList[n:] + someList[:n]
would solve your purpose if n <= len(someList)
Also, collections.deque is the efficient way.
I believe this is what you want
>>> def startAt(index, list):
... print list[index:] + list[:index]
...
>>> l = [0,1,2,3,4,5]
>>> startAt(3, l)
[3, 4, 5, 0, 1, 2]
>>>