Questions tagged [list]
The list tag may refer to: a linked list (an ordered set of nodes, each referencing its successor), or a form of dynamic array. Not to be used for HTML lists, use [html-lists] instead.
142,713
questions
535
votes
21
answers
1.5m
views
How can I compare two lists in python and return matches [duplicate]
I want to take two lists and find the values that appear in both.
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
would return [5], for instance.
530
votes
5
answers
335k
views
How to add item to the beginning of List<T>?
I want to add a "Select One" option to a drop down list bound to a List<T>.
Once I query for the List<T>, how do I add my initial Item, not part of the data source, as the FIRST element ...
527
votes
20
answers
384k
views
How to get the Cartesian product of multiple lists
How can I get the Cartesian product (every possible combination of values) from a group of lists?
For example, given
somelists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
How do I get this?
[(1, 'a',...
525
votes
13
answers
1.9m
views
How to initialize List<String> object in Java?
I can not initialize a List as in the following code:
List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
...
525
votes
13
answers
513k
views
C# LINQ find duplicates in List
Using LINQ, from a List<int>, how can I retrieve a list that contains entries repeated more than once and their values?
521
votes
20
answers
710k
views
Print a list in reverse order with range()?
How can you produce the following list with range() in Python?
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
514
votes
26
answers
685k
views
What is the difference between Set and List?
What is the fundamental difference between the Set<E> and List<E> interfaces?
514
votes
11
answers
392k
views
How to get the list of all installed color schemes in Vim?
Is there a way to get a list of all installed color schemes in Vim? That would make very easy to select one without looking at the .vim directory.
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]...
508
votes
17
answers
858k
views
How can I add an item to a IEnumerable<T> collection?
My question as title above. For example
IEnumerable<T> items = new T[]{new T("msg")};
items.ToList().Add(new T("msg2"));
but after all it only has 1 item inside. Can we have ...
500
votes
11
answers
358k
views
Combine a list of data frames into one data frame by row
I have code that at one place ends up with a list of data frames which I really want to convert to a single big data frame.
I got some pointers from an earlier question which was trying to do ...
500
votes
12
answers
478k
views
ArrayList vs List<> in C#
What is the difference between ArrayList and List<> in C#?
Is it only that List<> has a type while ArrayList doesn't?
488
votes
20
answers
585k
views
How to check if an object is a list or tuple (but not string)?
This is what I normally do in order to ascertain that the input is a list/tuple - but not a str. Because many times I stumbled upon bugs where a function passes a str object by mistake, and the target ...
485
votes
10
answers
796k
views
List<T> OrderBy Alphabetical Order
I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic List<T>. For the sake of this example, let's say I have a List of a Person type with a property of lastname. How would I ...
482
votes
9
answers
1.3m
views
How to declare and add items to an array in Python
I'm trying to add items to an array in Python.
I run
array = {}
Then, I try to add something to this array by doing:
array.append(valueToBeInserted)
There doesn't seem to be an .append method for ...
477
votes
21
answers
611k
views
Find intersection of two nested lists?
I know how to get an intersection of two flat lists:
b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
or
def intersect(a, b):
return list(set(a) & set(b))
...
464
votes
21
answers
1.3m
views
How to sort a List/ArrayList?
I have a List of doubles in java and I want to sort ArrayList in descending order.
Input ArrayList is as below:
List<Double> testList = new ArrayList();
testList.add(0.5);
testList.add(0.2);
...
464
votes
7
answers
859k
views
Python list sort in descending order
How can I sort this list in descending order?
timestamps = [
"2010-04-20 10:07:30",
"2010-04-20 10:07:38",
"2010-04-20 10:07:52",
"2010-04-20 10:08:...
464
votes
4
answers
2.1m
views
Check if something is (not) in a list in Python
I have a list of tuples in Python, and I have a conditional where I want to take the branch ONLY if the tuple is not in the list (if it is in the list, then I don't want to take the if branch)
if ...
461
votes
6
answers
1.2m
views
Getting a list item by index
I've recently started using c# moving over from Java. I can't seem to find how to get a list item by index. In java to get the first item of the list it would be:
list1.get(0);
What is the ...
459
votes
10
answers
724k
views
How to split by comma and strip white spaces in Python?
I have some python code that splits on comma, but doesn't strip the whitespace:
>>> string = "blah, lots , of , spaces, here "
>>> mylist = string.split(',')
>>> print ...
453
votes
26
answers
2.2m
views
Sum a list of numbers in Python [duplicate]
Given a list of numbers such as:
[1, 2, 3, 4, 5, ...]
How do I calculate their total sum:
1 + 2 + 3 + 4 + 5 + ...
How do I calculate their pairwise averages:
[(1+2)/2, (2+3)/2, (3+4)/2, (4+5)/2, ...]...
452
votes
11
answers
376k
views
Python list vs. array – when to use?
If you are creating a 1d array, you can implement it as a list, or else use the 'array' module in the standard library. I have always used lists for 1d arrays.
What is the reason or circumstance ...
448
votes
8
answers
418k
views
How to take the first N items from a generator or list? [duplicate]
With linq I would
var top5 = array.Take(5);
How to do this with Python?
438
votes
5
answers
642k
views
How to get last items of a list in Python?
I need the last 9 numbers of a list and I'm sure there is a way to do it with slicing, but I can't seem to get it. I can get the first 9 like this:
num_list[0:9]
434
votes
9
answers
1.1m
views
How to get the first element of the List or Set? [duplicate]
I'd like to know if I can get the first element of a list or set. Which method to use?
434
votes
10
answers
1.2m
views
Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?
I have a Numpy array consisting of a list of lists, representing a two-dimensional array with row labels and column names as shown below:
data = np.array([['','Col1','Col2'],['Row1',1,2],['Row2',3,4]])...
429
votes
6
answers
921k
views
How to append multiple values to a list in Python
I am trying to figure out how to append multiple values to a list in Python. I know there are few methods to do so, such as manually input the values, or put the append operation in a for loop, or the ...
423
votes
6
answers
631k
views
Convert NumPy array to Python list
How do I convert a NumPy array into a Python List?
419
votes
11
answers
1.3m
views
Finding and replacing elements in a list
I have to search through a list and replace all occurrences of one element with another. So far my attempts in code are getting me nowhere, what is the best way to do this?
For example, suppose my ...
416
votes
13
answers
589k
views
Add list to set
How do I add a list of values to an existing set?
414
votes
15
answers
580k
views
Determine if string is in list in JavaScript
In SQL we can see if a string is in a list like so:
Column IN ('a', 'b', 'c')
What's a good way to do this in JavaScript? It's so clunky to do this:
if (expression1 || expression2 || str === 'a' || ...
409
votes
8
answers
462k
views
How to easily initialize a list of Tuples?
I love tuples. They allow you to quickly group relevant information together without having to write a struct or class for it. This is very useful while refactoring very localized code.
Initializing a ...
408
votes
13
answers
285k
views
Why doesn't list have safe "get" method like dictionary?
Why doesn't list have a safe "get" method like dictionary?
>>> d = {'a':'b'}
>>> d['a']
'b'
>>> d['c']
KeyError: 'c'
>>> d.get('c', 'fail')
'fail'
>>> l =...
407
votes
6
answers
307k
views
Pandas DataFrame to List of Dictionaries
I have the following DataFrame:
customer item1 item2 item3
1 apple milk tomato
2 water orange potato
3 juice mango chips
which I want ...
407
votes
10
answers
457k
views
Find object in list that has attribute equal to some value (that meets any condition)
I've got a list of objects. I want to find one (first or whatever) object in this list that has an attribute (or method result - whatever) equal to value.
What's the best way to find it?
Here's a test ...
406
votes
3
answers
378k
views
Splitting on last delimiter in Python string?
What's the recommended Python idiom for splitting a string on the last occurrence of the delimiter in the string? example:
# instead of regular split
>> s = "a,b,c,d"
>> s.split(",")
>&...
404
votes
2
answers
312k
views
Find first sequence item that matches a criterion [duplicate]
What would be the most elegant and efficient way of finding/returning the first list item that matches a certain criterion?
For example, if I have a list of objects and I would like to get the first ...
403
votes
32
answers
347k
views
Array or List in Java. Which is faster?
I have to keep thousands of strings in memory to be accessed serially in Java. Should I store them in an array or should I use some kind of List ?
Since arrays keep all the data in a contiguous chunk ...
403
votes
5
answers
174k
views
Flatten List in LINQ
I have a LINQ query which returns IEnumerable<List<int>> but i want to return only List<int> so i want to merge all my record in my IEnumerable<List<int>> to only one ...
401
votes
4
answers
210k
views
Scala list concatenation, ::: vs ++
Is there any difference between ::: and ++ for concatenating lists in Scala?
scala> List(1,2,3) ++ List(4,5)
res0: List[Int] = List(1, 2, 3, 4, 5)
scala> List(1,2,3) ::: List(4,5)
res1: List[...
400
votes
10
answers
497k
views
How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it? [duplicate]
I'm trying to remove some elements from an ArrayList while iterating it like this:
for (String str : myArrayList) {
if (someCondition) {
myArrayList.remove(str);
}
}
Of course, I get ...
391
votes
13
answers
862k
views
Convert a list with strings all to lowercase or uppercase [duplicate]
I have a Python list variable that contains strings. Is there a function that can convert all the strings in one pass to lowercase and vice versa, uppercase?
391
votes
40
answers
294k
views
How can I partition (split up, divide) a list based on a condition?
I have some code like:
good = [x for x in mylist if x in goodvals]
bad = [x for x in mylist if x not in goodvals]
The goal is to split up the contents of mylist into two other lists, based on whether ...
390
votes
11
answers
412k
views
Remove duplicates in the list using linq
I have a class Items with properties (Id, Name, Code, Price).
The List of Items is populated with duplicated items.
For ex.:
1 Item1 IT00001 $100
2 Item2 ...
387
votes
7
answers
460k
views
Is there a concurrent List in Java's JDK?
How can I create a concurrent List instance, where I can access elements by index? Does the JDK have any classes or factory methods I can use?
386
votes
9
answers
541k
views
How can I convert each item in the list to string, for the purpose of joining them? [duplicate]
I need to join a list of items. Many of the items in the list are integer values returned from a function; i.e.,
myList.append(munfunc())
How should I convert the returned result to a string in ...
384
votes
14
answers
368k
views
Transpose list of lists
Let's take:
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The result I'm looking for is
r = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
and not
r = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
381
votes
5
answers
198k
views
Difference between a Seq and a List in Scala
I've seen in many examples that sometimes a Seq is being used, while other times is the List...
Is there any difference, other than the former one being a Scala type and the List coming from Java?
380
votes
13
answers
463k
views
Split a Pandas column of lists into multiple columns
I have a Pandas DataFrame with one column:
import pandas as pd
df = pd.DataFrame({"teams": [["SF", "NYG"] for _ in range(7)]})
teams
0 [SF, NYG]
1 [SF, NYG]
2 ...