All Questions

Tagged with
Filter by
Sorted by
Tagged with
5432 votes
28 answers
4.4m views

How to access the index value in a 'for' loop?

How do I access the index while iterating over a sequence with a for loop? xs = [8, 23, 45] for x in xs: print("item #{} = {}".format(index, x)) Desired output: item #1 = 8 item #2 = ...
Joan Venge's user avatar
  • 323k
698 votes
40 answers
258k views

How to iterate over a list in chunks

I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list ...
Ben Blank's user avatar
  • 55.7k
610 votes
28 answers
562k views

How to remove elements from a generic list while iterating over it?

I am looking for a better pattern for working with a list of elements which each need processed and then depending on the outcome are removed from the list. You can't use .Remove(element) inside a ...
InvertedAcceleration's user avatar
511 votes
15 answers
555k views

How can I avoid "RuntimeError: dictionary changed size during iteration" error?

Suppose I have a dictionary of lists: d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]} Now I want to remove key-value pairs where the values are empty lists. I tried this code: for i in d: if not d[i]...
user1530318's user avatar
  • 26.4k
309 votes
7 answers
659k views

How do I loop through a list by twos? [duplicate]

I want to loop through a Python list and process 2 list items at a time. Something like this in another language: for(int i = 0; i < list.length(); i+=2) { // do something with list[i] and list[...
froadie's user avatar
  • 81.4k
160 votes
9 answers
285k views

How to for_each through a list(objects) in Terraform 0.12

I need to deploy a list of GCP compute instances. How do I loop for_each through the "vms" in a list of objects like this: "gcp_zone": "us-central1-a", "...
TheShadow2707's user avatar
156 votes
4 answers
238k views

Check if list<t> contains any of another list

I have a list of parameters like this: public class parameter { public string name {get; set;} public string paramtype {get; set;} public string source {get; set;} } IEnumerable<...
gdp's user avatar
  • 8,122
148 votes
6 answers
174k views

Iterate through adjacent pairs of items in a Python list [duplicate]

Is it possible to iterate a list in the following way in Python (treat this code as pseudocode)? a = [5, 7, 11, 4, 5] for v, w in a: print [v, w] And it should produce [5, 7] [7, 11] [11, 4] [4, ...
marvin_yorke's user avatar
  • 3,509
145 votes
7 answers
210k views

Python : List of dict, if exists increment a dict value, if not append a new dict

I would like do something like that. list_of_urls = ['http://www.google.fr/', 'http://www.google.fr/', 'http://www.google.cn/', 'http://www.google.com/', 'http://www....
Natim's user avatar
  • 17.7k
142 votes
5 answers
263k views

Iterating Over Dictionary Key Values Corresponding to List in Python

Working in Python 2.7. I have a dictionary with team names as the keys and the amount of runs scored and allowed for each team as the value list: NL_East = {'Phillies': [645, 469], 'Braves': [599, ...
Burton Guster's user avatar
118 votes
6 answers
165k views

Loop through list with both content and index [duplicate]

It is very common for me to loop through a python list to get both the contents and their indexes. What I usually do is the following: S = [1,30,20,30,2] # My list for s, i in zip(S, range(len(S))): ...
Oriol Nieto's user avatar
  • 5,449
118 votes
3 answers
140k views

Extract list of attributes from list of objects in python

I have an uniform list of objects in python: class myClass(object): def __init__(self, attr): self.attr = attr self.other = None objs = [myClass (i) for i in range(10)] Now I ...
lanwatch's user avatar
  • 1,407
101 votes
12 answers
24k views

Strange result when removing item from a list while iterating over it in Python

I've got this piece of code: numbers = list(range(1, 50)) for i in numbers: if i < 20: numbers.remove(i) print(numbers) But, the result I'm getting is: [2, 4, 6, 8, 10, 12, 14, 16, ...
Finger twist's user avatar
  • 3,676
85 votes
6 answers
429k views

Creating a list of objects in Python

I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are ...
77 votes
7 answers
157k views

Modifying list while iterating [duplicate]

l = range(100) for i in l: print i, print l.pop(0), print l.pop(0) The above python code ...
Xolve's user avatar
  • 22.7k
61 votes
3 answers
60k views

LINQ: How to skip one then take the rest of a sequence

i would like to iterate over the items of a List<T>, except the first, preserving the order. Is there an elegant way to do it with LINQ using a statement like: foreach (var item in list.Skip(...
Marcel's user avatar
  • 15.4k
60 votes
2 answers
128k views

Groovy, how to iterate a list with an index

With all the shorthand ways of doing things in Groovy, there's got to be an easier way to iterate a list while having access to an iteration index. for(i in 0 .. list.size()-1) { println list.get(...
raffian's user avatar
  • 31.7k
59 votes
6 answers
109k views

Change a value in mutable list in Kotlin

I got this mutablelist: [Videos(id=4, yt_id=yRPUkDjwr1A, title=test4, likes=0, kat=pranks, ilike=false), Videos(id=3, yt_id=WkyUU9ZDUto, title=test3, likes=0, kat=pranks, ilike=false), Videos(id=2, ...
TheGreatCornholio's user avatar
57 votes
8 answers
74k views

Process a list with a loop, taking 100 elements each time and automatically less than 100 at the end of the list

Is there a way to use a loop that takes the first 100 items in a big list, does something with them, then the next 100 etc but when it is nearing the end it automatically shortens the "100" step to ...
SecondLemon's user avatar
40 votes
5 answers
46k views

Can't modify list elements in a loop [duplicate]

While looping over a list in Python, I was unable to modify the elements without a list comprehension. For reference: li = ["spam", "eggs"] for i in li: i = "foo" li ...
user2717129's user avatar
40 votes
6 answers
105k views

Better/Faster to Loop through set or list?

If I have a python list that is has many duplicates, and I want to iterate through each item, but not through the duplicates, is it best to use a set (as in set(mylist), or find another way to create ...
askewchan's user avatar
  • 45.8k
35 votes
4 answers
13k views

Loop over 2 lists, repeating the shortest until end of longest [duplicate]

I am sure there is an easy and obvious way to do this, but I have been googling and reading the docs and I just cannot find anything. This is what I want to achieve: la = ['a1', 'a2', 'a3', 'a4'] lb ...
Mathias Nielsen's user avatar
34 votes
3 answers
4k views

Modify list and dictionary during iteration, why does it fail on dict?

Let's consider this code which iterates over a list while removing an item each iteration: x = list(range(5)) for i in x: print(i) x.pop() It will print 0, 1, 2. Only the first three ...
ducminh's user avatar
  • 1,332
32 votes
4 answers
25k views

Iterating over two lists one after another

I have two lists list1 and list2 of numbers, and I want to iterate over them with the same instructions. Like this: for item in list1: print(item.amount) print(item.total_amount) for item in ...
zardav's user avatar
  • 1,180
30 votes
9 answers
24k views

Removing Item From List - during iteration - what's wrong with this idiom? [duplicate]

As an experiment, I did this: letters=['a','b','c','d','e','f','g','h','i','j','k','l'] for i in letters: letters.remove(i) print letters The last print shows that not all items were removed ? (...
monojohnny's user avatar
  • 6,055
29 votes
4 answers
49k views

How can you split a list every x elements and add those x amount of elements to an new list?

I have a list of multiple integers and strings ['-200', ' 0', ' 200', ' 400', ' green', '0', '0', '200', '400', ' yellow', '200', '0', '200', '400', ' red'] I'm having difficulty separating the ...
Tyler's user avatar
  • 1,993
24 votes
1 answer
34k views

lapply function /loops on list of lists R

I know this topic appeared on SO a few times, but the examples were often more complicated and I would like to have an answer (or set of possible solutions) to this simple situation. I am still ...
MIH's user avatar
  • 1,083
23 votes
3 answers
111k views

Building a list in a loop in R - getting item names correct

I have a function which contains a loop over two lists and builds up some calculated data. I would like to return these data as a lists of lists, indexed by some value, but I'm getting the assignment ...
Hassantm's user avatar
  • 563
22 votes
3 answers
32k views

Put multiple data frames into list (smart way) [duplicate]

Is it possible to put a lot of data frames into a list in some easy way? Meaning instead of having to write each name manually like the following way: list_of_df <- list(data_frame1,data_frame2,...
Martin Petri Bagger's user avatar
21 votes
7 answers
46k views

Removing Items in a List While Iterating Through It with For Each Loop

I have a list named NeededList I need to check each item in this list to see if it exists in my database. If it does exist in the database I need to remove it from the list. But I can't change the ...
gromit1's user avatar
  • 587
20 votes
2 answers
71k views

Create array of json objects using for loops

I'm attempting to extract values from an html and then convert them into a json array, and so far I have been able to get what I want, but only as separate strings: I did two for loops: for line in ...
geekiechic's user avatar
19 votes
6 answers
9k views

Python strange behavior with enumerate

I know I'm not supposed to modify the list inside a loop, but just out of curiosity, I would like to know why the number of iterations is different between the following two examples. Example 1: x = ...
dbdq's user avatar
  • 355
17 votes
9 answers
39k views

How to loop through the alphabet via underscoreJS

I'm using Underscore's template() method in BackboneJS views. I'd like to show a list of alphabet letters in my view in order to sort a collection by letter. As a result, I have a list of 26 links (...
JeremyW's user avatar
  • 713
17 votes
5 answers
99k views

Assigning values to variables in a list using a loop

var_list = [one, two, three] num = 1 for var in var_list: var = num num += 1 The above gives me an error that 'one' doesn't exist. Can you not assign in this way? I want to assign an ...
johnharris85's user avatar
16 votes
6 answers
16k views

How to flatten all items from a nested Java Collection into a single List?

Given a complex nested collection of objects such as: Set<List<Map<String, List<Object>>>> complexNestedCollection; Does a generic method exist to flatten this out and get a ...
Steve Chambers's user avatar
16 votes
4 answers
52k views

How to use tqdm to iterate over a list

I would like to know how long it takes to process a certain list. for a in tqdm(list1): if a in list2: #do something but this doesnt work. If I use for a in tqdm(range(list1)) i wont be ...
user2505650's user avatar
  • 1,353
16 votes
5 answers
49k views

Java iterate over ArrayList with HashMap in it

I have a Hashmap with four answers. And I have for ex 2 questions. This is how i do it // Awnsers question 1 antwoorden1.put("Hypertext Preprocessor", true); antwoorden1.put("Hypertext ...
Bham's user avatar
  • 245
16 votes
3 answers
25k views

replace index values in pandas dataframe with values from list

I have a dataframe and 2 lists. the 1st list gives a set of index values from the dataframe I want to replace the 2nd list gives the values I want to use I don't want to touch any of the other ...
kiltannen's user avatar
  • 1,117
16 votes
4 answers
24k views

Access list element using get()

I'm trying to use get() to access a list element in R, but am getting an error. example.list <- list() example.list$attribute <- c("test") get("example.list") # Works just ...
mike's user avatar
  • 23.3k
16 votes
6 answers
18k views

Iterate over a dict or list in Python

Just wrote some nasty code that iterates over a dict or a list in Python. I have a feeling this was not the best way to go about it. The problem is that in order to iterate over a dict, this is the ...
Chris Dutrow's user avatar
  • 49.6k
16 votes
6 answers
509 views

Traversing a list of lists by index within a loop, to reformat strings

I have a list of lists that looks like this, that was pulled in from a poorly formatted csv file: DF = [['Customer Number: 001 '], ['Notes: Bought a ton of stuff and was easy to deal with'], ['...
tumultous_rooster's user avatar
15 votes
4 answers
15k views

Remove elements as you traverse a list in Python [duplicate]

In Java I can do by using an Iterator and then using the .remove() method of the iterator to remove the last element returned by the iterator, like this: import java.util.*; public class ...
user102008's user avatar
15 votes
4 answers
198k views

Why do I get "List index out of range" when trying to add consecutive numbers in a list using "for i in list"? [duplicate]

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 ...
Dance Party2's user avatar
  • 7,334
15 votes
3 answers
15k views

How to iterate in a cartesian product of lists

I would like to iterate in a for loop using 3 (or any number of) lists with any number of elements, for example: from itertools import izip for x in izip(["AAA", "BBB", "CCC"], ["M", "Q", "S", "K", "...
alwbtc's user avatar
  • 28.8k
15 votes
4 answers
69k views

How to check whether a List<String> contains a specific string?

Here's what I'm trying to do: I have some List<String>, I want to print a statement if the List contains a particular string, else throw an Exception but when I try the following code List<...
DjShon's user avatar
  • 243
15 votes
2 answers
49k views

Generating a json in a loop in python

I have some difficulties generating a specific JSON object in python. I need it to be in this format: [ {"id":0 , "attributeName_1":"value" , "attributeName_2&...
Below the Radar's user avatar
15 votes
3 answers
17k views

Counting 2d lists in python

How can I count the number of items that are 'hit' in this 2d list?? grid = [['hit','miss','miss','hit','miss'], ['miss','miss','hit','hit','miss'], ['miss','miss','miss','hit','hit'], ...
user2212774's user avatar
15 votes
5 answers
2k views

Python splitting list to sublists at given start/end keywords

If I were to have a list, say lst = ['hello', 'foo', 'test', 'world', 'bar', 'idk'] I'd like to split it into a sublist with 'foo' and 'bar' as start and end keywords, so that I would get lst = ['...
Leo Whitehead's user avatar
14 votes
4 answers
21k views

Python loops with multiple lists? [duplicate]

<edit> Thanks to everyone who has answered so far. The zip and os.path.join are really helpful. Any suggestions on ways to list the counter in front, without doing something like this: zip(range(...
user avatar
14 votes
6 answers
23k views

Why does a for-loop with pop-method (or del statement) not iterate over all list elements [duplicate]

I am new to Python and experimenting with lists I am using Python 3.2.3 (default, Oct 19 2012, 20:13:42), [GCC 4.6.3] on linux2 Here is my samplecode >>> l=[1,2,3,4,5,6] >>> for i ...
user1913757's user avatar

1
2 3 4 5
88