This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to iterate over two lists - python
I want to iterate over two items at the same time, an iteration that in my mind looks like this:
for elem1 in list 1 and for elem2 in list2:
do something to elem1; do something to elem2
This syntax, however, is not acceptable. To be clear, I'm not talking about nested for loops, because then I'd be iterating over an entire list for every element in the first list. I want to iterate over the two lists (or whatever) in tandem. Is there a pythonic way to do this?
Use zip():
for elem1, elem2 in zip(list1, list2):
If one of these lists is longer than the other, you won't see the elements beyond the length of the shorter list.
On python 2, zip() results in a copy of both lists zipped together, and for large lists that can be a memory burden. Use itertools.izip() for such larger lists, it returns an iterator instead. On python 3, zip() itself already returns an iterator.
If you need to loop over the longest list instead (and fill in a filler value for the missing shorter list elements), use itertools.izip_longest() instead:
from itertools import izip_longest
for elem1, elem2 in izip_longest(list1, list2):
Related
This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 10 months ago.
I have a code which takes input of the users and creates a nested list.
List = [list 1, list2, list 3,.....]
The list 1, list 2, list 3 and so on are dynamic and can keep increasing or decreasing.
So far my code output is:
All_data = [[a,b],[c,d],[1,2],[3,4],.....]
The output that I want (for the dynamic nested list):
All_data = [a,b,c,d,1,2,3,4,......]
Can anyone suggest me a solution to solve this?
You can use itertools.chain:
itertools.chain(*All_data)
Or:
itertools.chain.from_iterable(All_data)
This creates an iterator, if you want to get a list:
list(itertools.chain.from_iterable(All_data))
You can use numpy.concatenate(). It will condense the nested list into a single list.
If your nested list is dynamic and can grow exponentially, then I will suggest to use itertools.chain.from_iterable() from itertools library. It will be faster because it will not convert the list into a numpy array like the first option.
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 12 months ago.
I was trying to sort a list using for loops in python.
I wrote the code like this.
L=[1,2,3,6,7,9,4]
NL=[]
for i in L:
NL.append(min(L))
L.remove(min(L))
print(NL)
But here the output is [1, 2, 3, 4].
I can't understand why the output is stopping at 4. I am new to coding. It would be helpful if someone could help me with this.
You're removing elements from a list while looping over it, which is problematic (if the index of the element you're removing is before your current loop index, the "next element" being shifted back by one won't be visited). As you don't need to work with the index anyways, you can simply loop n times, where n is the number of elements in the list (the length of the list):
L=[1,2,3,6,7,9,4]
NL=[]
for _ in range(len(L)):
NL.append(min(L))
L.remove(min(L))
print(NL)
Side note: The algorithm you've implemented is called "selectionsort" and has quadratic time complexity. You're also emptying the input list. In practice, you should usually be using Python's builtin [...].sort() to sort the input list in place; if you want a sorted copy, you can always call [...].copy() first.
This question already has answers here:
Iterating over two lists one after another
(4 answers)
Closed 4 years ago.
I would like to create a list from elements of 2 different lists using list comprehensions.
For instance, assuming my 2 lists are men and women, I want a single list with all names:
men_names = [man.name for man in men]
women_names = [woman.name for woman in women]
all_names = men_names + women_names
Is there a one-line solution to obtain this list? Thanks!
EDIT: Using a list comprehension is a requirement because in my particular case it should be very much faster than building the list in a for loop, and performance is an issue.
Using itertools.chain is a way to achieve this without creating an intermediate list.
from itertools import chain
all_names = [person.name for person in chain(men, women)]
This question already has answers here:
python - get list of tuples first index?
(5 answers)
Closed 6 years ago.
I have a list of tuples in this format:
my_list = [(1,4),(3,6),(10,7)]
I want to print the second elements of each tupple:
4,6,7
I can access those values as:
my_list[0][1]
my_list[1][1]
my_list[2][1]
But that isn't a reasonable approach for any reasonable size list, for now, and doing using list comprehension:
[x[1] for x in my_list ]
Is there any solution that doesn't imply to use a loop?
something like:
my_list[:][1]
I tried to do it that way but got:
(3, 6)
[:] just creates a copy of the list, so [1] indexes that copy. And no, outside of NumPy arrays, there is technically no way to avoid a loop. The loop may be done in C code in a function like map(), but there's going to be a loop anyway.
Using map() for example applies a callable for each element in your input list:
map(lambda nested: nested[1], my_list)
or
from operator import itemgetter
map(itemgetter(1), my_list)
Both work in Python 2, in Python 3 you need to wrap the map() call in a list() call to drive the iteration.
Either way, I find a list comprehension to be clearer here anyway.
As mentioned in python get list of tuples first index
try with zip
my_list = [(1,4),(3,6),(10,7)]
print zip(*my_list)[1]
(4, 6, 7)
This question already has answers here:
How do I iterate over the tuples of the items of two or more lists in Python? [duplicate]
(9 answers)
Closed 7 years ago.
I am wondering if it's posiible to iterate over two lists at once.
Something like that:
for x, m in list1, list2:
...
I know that I should use the '.items()', but I don't want to create dictionary from two lists.
Any ideas?
Use zip.
for x, m in zip(list1, list2):
zip(*iterables)
Make an iterator that aggregates elements from each of the iterables.
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.