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,698
questions
300
votes
7
answers
1.1m
views
Python - Count elements in list [duplicate]
I am trying to find a simple way of getting a count of the number of elements in a list:
MyList = ["a", "b", "c"]
I want to know there are 3 elements in this list.
299
votes
7
answers
1.2m
views
Converting Dictionary to List? [duplicate]
I'm trying to convert a Python dictionary into a Python list, in order to perform some calculations.
#My dictionary
dict = {}
dict['Capital']="London"
dict['Food']="Fish&Chips"
dict['2012']="...
299
votes
9
answers
203k
views
Java List.add() UnsupportedOperationException
I try to add objects to a List<String> instance but it throws an UnsupportedOperationException.
Does anyone know why?
My Java code:
String[] membersArray = request.getParameterValues('members')...
298
votes
11
answers
1.0m
views
Initialising an array of fixed size in Python [duplicate]
I would like to know how i can initialize an array(or list), yet to be populated with values, to have a defined size.
For example in C:
int x[5]; /* declared without adding elements*/
How do I do ...
297
votes
5
answers
162k
views
What is the difference between List.of and Arrays.asList?
Java 9 introduced new factory methods for lists, List.of:
List<String> strings = List.of("first", "second");
What's the difference between the previous and the new option? That is, what's the ...
295
votes
13
answers
372k
views
Appending the same string to a list of strings in Python
I am trying to take one string, and append it to every string contained in a list, and then have a new list with the completed strings. Example:
list1 = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
*...
295
votes
7
answers
154k
views
What is the difference between `sorted(list)` vs `list.sort()`?
list.sort() sorts the list and replaces the original list, whereas sorted(list) returns a sorted copy of the list, without changing the original list.
When is one preferred over the other?
Which is ...
294
votes
14
answers
622k
views
Java List.contains(Object with field value equal to x)
I want to check whether a List contains an object that has a field with a certain value. Now, I could use a loop to go through and check, but I was curious if there was anything more code efficient.
...
294
votes
9
answers
324k
views
Compare two List<T> objects for equality, ignoring order [duplicate]
Yet another list-comparing question.
List<MyType> list1;
List<MyType> list2;
I need to check that they both have the same elements, regardless of their position within the list. Each ...
291
votes
8
answers
237k
views
Shorter syntax for casting from a List<X> to a List<Y>?
I know it's possible to cast a list of items from one type to another (given that your object has a public static explicit operator method to do the casting) one at a time as follows:
List<Y> ...
291
votes
10
answers
961k
views
How to remove item from list in C#?
I have a list stored in resultlist as follows:
var resultlist = results.ToList();
It looks something like this:
ID FirstName LastName
-- --------- --------
1 Bill Smith
2 John ...
291
votes
11
answers
302k
views
Remove items from one list in another
I'm trying to figure out how to traverse a generic list of items that I want to remove from another list of items.
So let's say I have this as a hypothetical example
List<car> list1 = ...
291
votes
11
answers
873k
views
Convert tuple to list and back
I'm currently working on a map editor for a game in pygame, using tile maps.
The level is built up out of blocks in the following structure (though much larger):
level1 = (
(1,1,1,1,1,1)
...
289
votes
12
answers
337k
views
Convert Iterator to List
Given Iterator<Element>, how can we conveniently convert that Iterator to a List<Element>, so that we can use List's operations on it such as get(index), add(element), etc.
289
votes
4
answers
821k
views
Select distinct using linq [duplicate]
I have a class list of class
public class LinqTest
{
public int id { get; set; }
public string value { get; set; }
}
List<LinqTest> myList = new List<LinqTest>();
myList.Add(new LinqTest(...
288
votes
33
answers
700k
views
How to count the frequency of the elements in an unordered list? [duplicate]
Given an unordered list of values like
a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
How can I get the frequency of each value that appears in the list, like so?
# `a` has 4 instances of `1`, 4 of `2`, ...
288
votes
7
answers
213k
views
How do I find a list of Homebrew's installable packages?
Recently I installed Brew. How can I retrieve a list of available brew packages to install?
287
votes
14
answers
533k
views
Common elements comparison between 2 lists
Given two input lists, how can I create a list of the elements that are common to both inputs?
For example: for inputs [1,2,3,4,5,6] and [3,5,7,9], the result should be [3, 5]; for inputs ['this','...
287
votes
15
answers
302k
views
Can you remove elements from a std::list while iterating through it?
I've got code that looks like this:
for (std::list<item*>::iterator i = items.begin(); i != items.end(); i++)
{
bool isActive = (*i)->update();
//if (!isActive)
// items.remove(*...
285
votes
10
answers
413k
views
Using a dictionary to count the items in a list
Suppose I have a list of items, like:
['apple', 'red', 'apple', 'red', 'red', 'pear']
I want a dictionary that counts how many times each item appears in the list. So for the list above the result ...
285
votes
29
answers
799k
views
Finding median of list in Python
How do you find the median of a list in Python? The list can be of any size and the numbers are not guaranteed to be in any particular order.
If the list contains an even number of elements, the ...
285
votes
9
answers
690k
views
Initializing a list to a known number of elements in Python [duplicate]
Right now I am using a list, and was expecting something like:
verts = list (1000)
Should I use array instead?
284
votes
3
answers
251k
views
Pass a list to a function to act as multiple arguments [duplicate]
In a function that expects a list of items, how can I pass a Python list item without getting an error?
my_list = ['red', 'blue', 'orange']
function_that_needs_strings('red', 'blue', 'orange') # works!...
283
votes
11
answers
325k
views
How can I match up permutations of a long list with a shorter list (according to the length of the shorter list)? [duplicate]
I’m having trouble wrapping my head around a algorithm I’m try to implement. I have two lists and want to take particular combinations from the two lists.
Here’s an example.
names = ['a', 'b']
numbers ...
282
votes
15
answers
362k
views
How can I multiply all items in a list together with Python?
Given a list of numbers like [1,2,3,4,5,6], how can I write code to multiply them all together, i.e. compute 1*2*3*4*5*6?
280
votes
2
answers
236k
views
Unpacking a list / tuple of pairs into two lists / tuples [duplicate]
I have a list that looks like this:
my_list = [('1','a'),('2','b'),('3','c'),('4','d')]
I want to separate the list in 2 lists.
list1 = ['1','2','3','4']
list2 = ['a','b','c','d']
I can do it for ...
279
votes
13
answers
659k
views
Calculating arithmetic mean (one type of average) in Python [duplicate]
Is there a built-in or standard library method in Python to calculate the arithmetic mean (one type of average) of a list of numbers?
279
votes
3
answers
158k
views
How to add multiple objects to ManyToMany relationship at once in Django ?
Based on the Django doc, I should be able to pass multiple objects at once to be added to a manytomany relationship but I get a
* TypeError: unhashable type: 'list'
when I try to pass a django ...
277
votes
10
answers
458k
views
How to deep copy a list?
After E0_copy = list(E0), I guess E0_copy is a deep copy of E0 since id(E0) is not equal to id(E0_copy). Then I modify E0_copy in the loop, but why is E0 not the same after?
E0 = [[1, 2, 3], [4, 5, 6],...
276
votes
19
answers
243k
views
Remove duplicate dict in list in Python
I have a list of dicts, and I'd like to remove the dicts with identical key and value pairs.
For this list: [{'a': 123}, {'b': 123}, {'a': 123}]
I'd like to return this: [{'a': 123}, {'b': 123}]
...
276
votes
8
answers
133k
views
Is there a zip-like function that pads to longest length?
Is there a built-in function that works like zip() but that will pad the results so that the length of the resultant list is the length of the longest input rather than the shortest input?
>>&...
275
votes
8
answers
598k
views
How to construct a set out of list items in python?
I have a list of filenames in python and I would want to construct a set out of all the filenames.
filelist=[]
for filename in filelist:
set(filename)
This does not seem to work. How can do this?...
272
votes
10
answers
354k
views
From list of integers, get number closest to a given value
Given a list of integers, I want to find which number is the closest to a number I give in input:
>>> myList = [4, 1, 88, 44, 3]
>>> myNumber = 5
>>> takeClosest(myList, ...
272
votes
14
answers
739k
views
How to create a drop-down list?
How can I create a drop-down list? I've tried a ScrollView but it's not exactly what I need.
270
votes
13
answers
354k
views
How to do a recursive sub-folder search and return files in a list?
I am working on a script to recursively go through subfolders in a mainfolder and build a list off a certain file type. I am having an issue with the script. It's currently set as follows:
for root, ...
270
votes
10
answers
378k
views
How do I make a list of data frames?
How do I make a list of data frames and how do I access each of those data frames from the list?
For example, how can I put these data frames in a list ?
d1 <- data.frame(y1 = c(1, 2, 3),
...
269
votes
11
answers
392k
views
How can I convert comma separated string into a List<int> [duplicate]
string tags = "9,3,12,43,2"
List<int> TagIds = tags.Split(',');
This doesn't work cause the split method returns a string[]
268
votes
9
answers
203k
views
How to randomize two ArrayLists in the same fashion?
I have two arraylist filelist and imgList which related to each other, e.g. "H1.txt" related to "e1.jpg". How to automatically randomized the list of imgList according to the randomization of fileList?...
268
votes
7
answers
504k
views
How to convert comma-delimited string to list in Python?
Given a string that is a sequence of several values separated by a commma:
mStr = 'A,B,C,D,E'
How do I convert the string to a list?
mList = ['A', 'B', 'C', 'D', 'E']
267
votes
15
answers
680k
views
How to extract all values from a dictionary in Python?
I have a dictionary d = {1:-0.3246, 2:-0.9185, 3:-3985, ...}.
How do I extract all of the values of d into a list l?
265
votes
9
answers
452k
views
List of lists into numpy array
How do I convert a simple list of lists into a numpy array? The rows are individual sublists and each row contains the elements in the sublist.
264
votes
17
answers
337k
views
Compute list difference [duplicate]
In Python, what is the best way to compute the difference between two lists?
example
A = [1,2,3,4]
B = [2,5]
A - B = [1,3,4]
B - A = [5]
263
votes
13
answers
236k
views
How can I convert a dictionary into a list of tuples?
If I have a dictionary like:
{'a': 1, 'b': 2, 'c': 3}
How can I convert it to this?
[('a', 1), ('b', 2), ('c', 3)]
And how can I convert it to this?
[(1, 'a'), (2, 'b'), (3, 'c')]
262
votes
11
answers
251k
views
Python Sets vs Lists
In Python, which data structure is more efficient/speedy? Assuming that order is not important to me and I would be checking for duplicates anyway, is a Python set slower than a Python list?
262
votes
8
answers
482k
views
Python 3 turn range to a list
I'm trying to make a list with numbers 1-1000 in it. Obviously this would be annoying to write/read, so I'm attempting to make a list with a range in it. In Python 2 it seems that:
some_list = range(...
261
votes
8
answers
419k
views
How to switch position of two items in a Python list?
I haven’t been able to find a good solution for this problem on the net (probably because switch, position, list and Python are all such overloaded words).
It’s rather simple – I have this list:
['...
260
votes
16
answers
268k
views
When to use a linked list over an array/array list?
I use a lot of lists and arrays but I have yet to come across a scenario in which the array list couldn't be used just as easily as, if not easier than, the linked list. I was hoping someone could ...
259
votes
9
answers
561k
views
SQL variable to hold list of integers
I'm trying to debug someone else's SQL reports and have placed the underlying reports query into a query windows of SQL 2012.
One of the parameters the report asks for is a list of integers. This is ...
258
votes
27
answers
402k
views
Find the most common element in a list
What is an efficient way to find the most common element in a Python list?
My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be ...
258
votes
15
answers
377k
views
How do I check if there are duplicates in a flat list?
For example, given the list ['one', 'two', 'one'], the algorithm should return True, whereas given ['one', 'two', 'three'] it should return False.