For loop syntax in Python without using range() or xrange() - python

I do not know much about python so i apologize if my question is a very basic one.
Let's say i have a list
lst = [1,2,3,4,5,6,7,8,9,10]
Now what i want to know is that if there is any way to write the following piece of code in python without using range() or xrange():
for i in lst:
for j in lst after element i: '''This is the line i want the syntax for'''
#Do Something
The second loop is to access elements after the element i i.e., if i = 3, j would have to loop through from 4 to 10, so the pairs of numbers if i and j are printed would be (1,2)..(1,10), (2,3)...(2,10), (3,4)..(3,10) etc.
I have no idea what to search for or what query to type on any search engine.
Any help would be much appreciated.

This is what list slicing is about, you can take part of your list from i'th element through
lst[i:]
furthermore, in order to have both index and value you need enumerate operation, which changes the list into list of pairs (index, value)
thus
for ind, i in enumerate(lst):
for j in lst[ind+1: ]:
#Do Something

It looks like you might want to use enumerate():
for index, item in enumerate(lst):
for j in lst[index+1:]:
#Do Something

Related

Printing list of list element one per line

Lets say i have a list of list containing:
[[1,'A'],[2,'B'],[3,'C']]
and i want to print it out as such:
1 A
2 B
3 C
I was thinking of using a for loop to print each element in the list of list but I wasn't quite sure of it.
lst = [[1,'A'],[2,'B'],[3,'C']]
for i in lst:
print(lst[i]) #perhaps needing to use \n in the loop?
You can unpack each nested list like this:
for num, let in lst:
print(num, let)
What you're currently doing, with for i in lst, is printing each element in lst, while you seem to think the for i in lst syntax, accompanying the lst[i] indexing, is, well, indexing the list. That's not how that works.
If you wanted your desired output while iterating in this fashion, try this:
for i in range(len(lst)):
print(' '.join(lst[i]))
More simply, you could do this:
for i in lst:
print(' '.join(i))
try this:
for i in lst:
print(i[0], i[1])

Creating a function that removes duplicates in list

I'm trying to manually make a function that removes duplicates from a list. I know there is a Python function that does something similar (set()), but I want to create my own. This is what I have:
def remove(lst):
for i in range(len(lst)):
aux = lst[0:i] + lst[i+1:len(lst)]
if lst[i] in aux:
del(lst[i])
return lst
I was trying something like creating a sub-list with all the items except the one the for is currently on, and then check if the item is still in the list. If it is, remove it.
The problem is that it gives me an index out of range error. Does the for i in range(len(lst)): line not update every time it starts over? Since I'm removing items from the list, the list will be shorter, so for a list that has 10 items and 2 duplicates, it will go up to index 9 instead of stopping on the 7th.
Is there anyway to fix this, or should I just try doing this is another way?
I know this does not fix your current script, but would something like this work?
def remove(lst):
unique=[]
for i in lst:
if i not in unique: unique.append(i)
return unique
Just simply looping through, creating another list and checking for membership?
The problem is you are manipulating the list as you are iterating over it. This means that when you reach the end of the list, it is now shorter because you're removed elements. You should (generally) avoid removing elements while you are looping over lists.
You got it the first time: len(lst) is evaluated only when you enter the loop. If you want it re-evaluated, try the while version:
i = 0
while i < len(lst):
...
i += 1
Next, you get to worry about another problem: you increment i only when you don't delete an item. When you do delete, shortening the list gets you to the next element.
i = 0
while i < len(lst):
aux = lst[0:i] + lst[i+1:len(lst)]
if lst[i] in aux:
del(lst[i])
else:
i += 1
I think that should solve your problem ... using the logic you intended.
def remove(lst):
new_list = []
for i in lst:
if i not in new_list:
new_list.append(i)
return new_list
You should append the values to a secondary list. As Bobbyrogers said, it's not a good idea to iterate over a list that is changing.
You can also try this:
lst = [1,2,3,3,4,4,5,6]
lst2 = []
for i in lst:
if i not in lst2:
lst2.append(i)
print(lst2)
[1, 2, 3, 4, 5, 6]

Python for loops has index for counter

Hello I'm beginner in Python and trying to read a part of a code with for loop but can't understand it, does any body knows how there is index over loop counter? Thanks
updateNodeNbrs = []
for a in nodeData:
updateNodeNbrs.append(a[0])
You're iterating directly over the elements of nodeData, so there is no need for an index. The current element is designated by a.
This is equivalent to:
updateNodeNbrs = []
for i in range(len(nodeData)):
updateNodeNbrs.append(nodeData[i][0])
Although the original code is more pythonic.
If you wanted to make the index appear, you could transform the code with enumerate to:
updateNodeNbrs = []
for i, a in enumerate(nodeData):
updateNodeNbrs.append(a[0])
And here, i would be the index of element a, and you could use it in the loop.
See same question here
If you have an existing list and you want to loop over it and keep track of the indices you can use the enumerate function. For example
l = ["apple", "pear", "banana"]
for i, fruit in enumerate(l):
print "index", i, "is", fruit

How does the enumerate function work?

I am supposed to do the following:
Define a function my_enumerate(items) that behaves in a similar way to the built-in enumerate function. It should return a list of pairs (i, item) where item is the ith item, with 0 origin, of the list items (see the examples below). Check the test cases for how the function should work. Your function must not call Python's in-built enumerate function.
Examples:
Input:
ans = my_enumerate([10, 20, 30])
print(ans)
Output:
[(0, 10), (1, 20), (2, 30)]
What does enumerate do? Try expressing it in English, and it may help you understand how to write the necessary code. If it doesn't then the practice of learning English language descriptions into code will be useful.
One way of describing enumerate is to say it iterates over each item in the list, and for each item in the input list it produces a pair of the item's index in the input list and the item.
So we know we need to iterate over the list:
for item in input_list:
pass
And we need to keep track of the index of the current item.:
index = 0
for item in input_list:
index += 1
Hmm, there's a better way of doing that:
for index in range(len(input_list)):
pass
Now to produce the pairs:
for index in range(len(input_list)):
pair = index, input_list[index]
You also need somewhere to store these pairs:
def my_enumerate(input_list):
output_list = []
for index in range(len(input_list)):
pair = index, input_list[index]
output_list.append(pair)
return output_list
Are there other ways to write code that produces the same output? Yes. Is this the best way to write this function? Not by a long shot. What this exercise should help you with is turning your thoughts into code, as you gain more experience doing that then you can combine multiple steps at a time, and start using more complicated programming concepts.
Use itertools.count and zip:
from itertools import count
def my_enumerate(values):
return list(zip(count(), values))

Easiest way to include a stop parameter in enumerate python?

Ss there a simple way to iterate over an iterable object that allows the specification of an end point, say -1, as well as the start point in enumerate. e.g.
for i, row in enumerate(myiterable, start=2): # will start indexing at 2
So if my object has a length of 10, what is the simplest way to to get it to start iterating at index 2 and stop iterating at index 9?
Alternatively, is there something from itertools that is more suitable for this. I am specifically interested in high performance methods.
In addition, when the start option was introduced in 2.6, is there any reason why a stop option was not?
Cheers
for i, row in enumerate(myiterable[2:], start=2):
if i>= limit: break
...
or
for i,row in itertools.takewhile(lambda (i,val):i < limit,enumerate(myiterable[2:],2)):
to rephrase the other suggestion (note that it will only work if your iterable is a sliceable object)
start,stop = 11,20
my_items = range(100)
for i,row in enumerate(my_items[start:stop],start):
....
I think you've misunderstood the 'start' keyword, it doesn't skip to the nth item in the iterable, it starts counting at n, for example:
for i, c in enumerate(['a', 'b', 'c'], start=5):
print i, c
gives:
5 a
6 b
7 c
For simple iterables like lists and tuples the simplest and fastest method is going to be something like:
obj = range(100)
start = 11
stop = 22
for i, item in enumerate(obj[start:stop], start=start):
pass
If I'm not going to be using the whole length of the iterable item, I find it easier to use something like:
for i in range(2, len(myiterable)):
instead of enumerate. And then index based on i within the loop. It requires less typing than other approaches that use enumerate.
Creating the slice of an iterable object could be expensive. To avoid this, use itertools.islice:
import itertools
for item in itertools.islice('abc', 0, 2):
print(item)
# will print:
1
2

Categories