All Questions

Tagged with
Filter by
Sorted by
Tagged with
1261 votes
9 answers
1.2m views

How do I iterate through two lists in parallel?

I have two iterables, and I want to go over them in pairs: foo = [1, 2, 3] bar = [4, 5, 6] for (f, b) in iterate_together(foo, bar): print("f:", f, " | b:", b) That should ...
Nathan Fellman's user avatar
315 votes
5 answers
528k views

How to check if all elements of a list match a condition?

I have a list that contains many sub-lists of 3 elements each, like: my_list = [["a", "b", 0], ["c", "d", 0], ["e", "f", 0], .....] The ...
alwbtc's user avatar
  • 28.8k
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
219 votes
6 answers
306k views

How to loop through all but the last item of a list? [duplicate]

Using a for loop, how can I loop through all except the last item in a list? I would like to loop through a list checking each item against the one following it. Can I do this without using indices?
David Sykes's user avatar
  • 49.1k
176 votes
6 answers
236k views

How to frame two for loops in list comprehension python

I have two lists as below tags = [u'man', u'you', u'are', u'awesome'] entries = [[u'man', u'thats'],[ u'right',u'awesome']] I want to extract entries from entries when they are in tags: result = [] ...
Shiva Krishna Bavandla's user avatar
117 votes
0 answers
7k views

What do two left angle brackets mean? [duplicate]

I saw a loop which I've never seen before: for (int i = 0; i < (1 << list.Count); i++) I can't understand what (1 << list.Count) means, maybe someone could explain me this?
user2412672's user avatar
  • 1,469
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
60 votes
4 answers
22k views

What is the meaning of list[:] in this code? [duplicate]

This code is from Python's Documentation. I'm a little confused. words = ['cat', 'window', 'defenestrate'] for w in words[:]: if len(w) > 6: words.insert(0, w) print(words) And the ...
S. Li's user avatar
  • 777
57 votes
1 answer
197k views

What does the "x for x in" syntax mean? [duplicate]

What actually happens when this code is executed: text = "word1anotherword23nextone456lastone333" numbers = [x for x in text if x.isdigit()] print(numbers) I understand, that [] makes a list, ....
Martin Melichar's user avatar
54 votes
13 answers
345k views

TypeError: 'list' object cannot be interpreted as an integer

The playSound function is taking a list of integers, and is going to play a sound for every different number. So if one of the numbers in the list is 1, 1 has a designated sound that it will play. ...
Greysus's user avatar
  • 641
50 votes
5 answers
190k views

ValueError: max() arg is an empty sequence

I've created a GUI using wxFormBuilder that should allow a user to enter the names of "visitors to a business" into a list and then click one of two buttons to return the most frequent and least ...
J'onn J'onzz's user avatar
48 votes
8 answers
251k views

How to iterate through a list of dictionaries

My code is index = 0 for key in dataList[index]: print(dataList[index][key]) Seems to work fine for printing the values of dictionary keys for index = 0. However, I can't figure out how to ...
C. P. Wagner's user avatar
46 votes
8 answers
15k views

How do I efficiently find which elements of a list are in another list?

I want to know which elements of list_1 are in list_2. I need the output as an ordered list of booleans. But I want to avoid for loops, because both lists have over 2 million elements. This is what I ...
herdek550's user avatar
  • 645
43 votes
4 answers
44k views

How to create all possible combinations from the elements of a list?

I have the following list: List(a, b, c, d, e) How to create all possible combinations from the above list? I expect something like: a ab abc
Shakti's user avatar
  • 2,013
40 votes
4 answers
130k views

python modify item in list, save back in list

I have a hunch that I need to access an item in a list (of strings), modify that item (as a string), and put it back in the list in the same index I'm having difficulty getting an item back into the ...
CQM's user avatar
  • 43.4k
29 votes
7 answers
99k views

How to get the previous element when using a for loop? [duplicate]

Possible Duplicates: Python - Previous and next values inside a loop python for loop, how to find next value(object)? I've got a list that contains a lot of elements, I iterate over the list ...
user469652's user avatar
29 votes
4 answers
205k views

Creating for loop until list.length

I'm reading about for loops right now, and I am curious if it's possible to do a for loop in Python like in Java. Is it even possible to do something like for (int i = 1; i < list.length; i++) ...
Agape's user avatar
  • 331
28 votes
3 answers
41k views

For-in loop requires '[UserVehicles]?' to conform to 'Sequence'; did you mean to unwrap optional? Swift

I have a data model which I made for API returns, it is something like this: struct VehicleData: Codable { let _embedded: Embedded } struct Embedded: Codable { let userVehicles: [...
XYD's user avatar
  • 661
26 votes
5 answers
32k views

Converting a list of data frames into individual data frames in R [duplicate]

I have been searching high and low for what I think is an easy solution. I have a large data frame that I split by factors. eqRegions <- split(eqDataAll, eqDataAll$SeismicRegion) This now ...
Bryan Butler's user avatar
  • 1,790
26 votes
4 answers
19k views

Java synchronized list for loop

Documentation on synchronizedList states that, It is imperative that the user manually synchronize on the returned list when iterating over it: List list = Collections.synchronizedList(new ArrayList(...
user927476's user avatar
25 votes
4 answers
183k views

python - if not in list [duplicate]

I have two lists: mylist = ['total','age','gender','region','sex'] checklist = ['total','civic'] I have to work with some code I have inherited which looks like this: for item in mylist: if ...
Boosted_d16's user avatar
  • 13.7k
24 votes
1 answer
125k views

Break for loop in an if statement [duplicate]

Currently having trouble with breaking this for loop. I want to break it if the variable is not found in this list so it can move two another for loop. It expects an indented block for the top of the ...
mansa's user avatar
  • 269
22 votes
4 answers
51k views

Using forloop.counter value as list index in a Django template

in my Django 1.1.1 application I've got a function in the view that returns to his template a range of numbers and a list of lists of items, for example: ... data=[[item1 , item2, item3], [item4, ...
Alex's user avatar
  • 255
20 votes
3 answers
48k views

Adding data frames as list elements (using for loop)

I have in my environment a series of data frames called EOG. There is one for each year between 2006 and 2012. Like, EOG2006, EOG2007...EOG2012. I would like to add them as elements of a list. First,...
Riccardo's user avatar
  • 753
19 votes
6 answers
13k views

How can I use a list comprehension to extend a list in python? [duplicate]

I'm not experienced in Python, and I often write code that (simplified) looks like this: accumulationList = [] for x in originalList: y = doSomething(x) accumulationList.append(y) return ...
Eric Wilson's user avatar
  • 58.5k
18 votes
3 answers
42k views

selenium.common.exceptions.InvalidArgumentException: Message: invalid argument error invoking get() with urls read from text file with Selenium Python

I have a list of URLs in a .txt file that I would like to run using selenium. Lets say that the file name is b.txt in it contains 2 urls (precisely formatted as below): https://www.google.com/,https:...
Sakyamooni's user avatar
17 votes
5 answers
10k views

List comprehension iterating over two lists is not working as expected [duplicate]

I want to iterate over two lists. The first list contains some browser user-agents and the second list contains versions of those browsers. I want to filter out only those user-agents whose version is ...
Viktor's user avatar
  • 1,046
16 votes
1 answer
58k views

Adding elements to a list in for loop in R

I'm trying to add elements to a list in a for loop. How can I set the field name? L <- list() for(i in 1:N) { # Create object Ps... string <- paste("element", ...
Darko's user avatar
  • 1,608
15 votes
4 answers
877 views

write better code instead of 2 for loops

I have 2 for loops and I want to make it better like list comprehension or lambda or else. how can i achieve the same? for example : filename = ['a.txt', 'b.txt', 'c.txt'] for files in filename: ...
sam's user avatar
  • 19k
15 votes
4 answers
64k views

How to convert a for loop output to a list?

For example: for y,x in zip(range(0,4,1),range(0,8,2)): print(x+y) Returns: 0 3 6 9 What I want is: ['0', '3', '6', '9'] How can I achieve this?
Sbioer's user avatar
  • 235
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
2 answers
11k views

Python - Any way to avoid several if-statements inside each other in a for-loop?

I need a better way to do this. I'm new with programming but I know that this is a very inefficient way of doing it and that I need a function for this, I just don't know how to do it exactly. any ...
user2966098's 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
12 votes
2 answers
22k views

l.append[i], object is not subscriptable? [closed]

When I do: l = [] for i in range(10): if i%3 == 0 or i%5 == 0: l.append[i] print sum(l) I get Traceback (most recent call last): File "PE1.py", line 4, in <module> l.append[...
Bentley4's user avatar
  • 10.8k
12 votes
1 answer
3k views

How to iterate over list of Dates without coercion to numeric?

This is related to Looping over a Date or POSIXct object results in a numeric iterator > dates <- as.Date(c("2013-01-01", "2013-01-02")) > class(dates) [1] "Date"...
user443854's user avatar
  • 7,286
11 votes
5 answers
112k views

How to create and fill a list of lists in a for loop

I'm trying to populate a list with a for loop. This is what I have so far: newlist = [] for x in range(10): for y in range(10): newlist.append(y) and at this point I am stumped. I was ...
CommanderPO's user avatar
11 votes
4 answers
27k views

Populate a list in Kotlin with a for loop

It's been a while that I just started to learn how to develop in Kotlin. There is this thing that I am working on, I am trying to parse a list into another type of list. Basically they are the same ...
Jona's user avatar
  • 263
11 votes
3 answers
45k views

create lists of unique names in a for -loop in python

I want to create a series of lists with unique names inside a for-loop and use the index to create the liste names. Here is what I want to do x = [100,2,300,4,75] for i in x: list_i=[] I want to ...
brain storm's user avatar
  • 30.7k
10 votes
4 answers
37k views

How to change variables fed into a for loop in list form

I am writing a basic program in Python that prompts the user to enter 5 test scores. The program will then convert each test score to a grade point (i.e. 4.0, 3.0, 2.0...), and then afterwards take ...
Dustin Burns's user avatar
10 votes
3 answers
4k views

python: using list slice as target of a for loop

I found this code snippet to be very interesting. a = [0, 1, 2, 3] for a[-1] in a: print(a) Output is as follows: [0, 1, 2, 0] [0, 1, 2, 1] [0, 1, 2, 2] [0, 1, 2, 2] I am trying to understand ...
Rishi P Bhatt's user avatar
9 votes
3 answers
3k views

Find first item with alphabetical precedence in list with numbers

Say I have a list object occupied with both numbers and strings. If I want to retrieve the first string item with the highest alphabetical precedence, how would I do so? Here is an example attempt ...
vs94's user avatar
  • 101
9 votes
5 answers
21k views

Loop print through two lists to get two columns with fixed(custom set) space between the first letter of each element of each list

Suppose I have these two lists: column1 = ["soft","pregnant","tall"] column2 = ["skin","woman", "man"] How do I loop print through these two lists while using a custom, fixed space(say 10, as in ...
Bentley4's user avatar
  • 10.8k
9 votes
4 answers
33k views

Change values in a list using a for loop (python)

I currently have some code that reads like this: letters = { 10 : "A", 11 : "B", 12 : "C", 13 : "D", 14 : "E", 15 : "F" } vallist = [rd1, rd2, gd1, gd2, bd1, bd2] for i in vallist: if i >= 10: ...
Kai036's user avatar
  • 310
9 votes
6 answers
2k views

Cycling values of a list [duplicate]

I'm new to coding and am trying to write a simple code that will take a list, say [1,2,3] and cycle the elements n number of times. So if n=1, I should get A=[3,1,2]. If n=2, I should get A=[2,3,1]....
DeathbyGreen's user avatar
9 votes
1 answer
2k views

Nested List comprehension in Python

I have a List inside of a List in Python and i want to convert them into a single list using List comprehension: >>> aa = [[1,2],[1,2]] >>> bb = [num for num in numbers for numbers ...
ellaRT's user avatar
  • 1,356
8 votes
5 answers
11k views

R remove objects from a list with if else statement

I have a list of data frames, and would like to remove those with less than 2 rows off from mylist: a<-data.frame(x=c(1:4),y=c("m", "n", "o", "p")) b<-data.frame(x=c(2:6),y=c("q", "w", "e", "r",...
lamushidi's user avatar
  • 303
8 votes
3 answers
2k views

In Python, are conditions in a loop re-evaluated before a new iteration is executed?

As with regards to python, when it comes to a for loop, will it re-evaluate the upper bound before re-iteration? Say I have the following scenario: def remove(self,list,element): for x in range(...
Andrew1024's user avatar
8 votes
1 answer
10k views

Populating a list with lm objects

I am trying to populate a named list with the results of an OLS in R. I tried li = list() for (i in 1:10) li[["RunOne"]][i] = lm(y~x) Here RunOne is a random name that designates the fitting run ...
ganesh reddy's user avatar
  • 1,872
8 votes
1 answer
14k views

Naming list items via loop in R

I want to take a list, create a String vector of the names of the list items, filling in blanks with a generic name and then set the names vector as the names of the list. My code works fine for ...
Siniyas's user avatar
  • 461
8 votes
2 answers
3k views

Adjust all nested lists to the same length

I am referring to this this specific answer Making nested lists same length. Since I don't have the permissions to comment yet and answering with a question to that topic would violate the rules, I am ...
McMo's user avatar
  • 151

1
2 3 4 5
84