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.

list
Filter by
Sorted by
Tagged with
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.
tehryan's user avatar
  • 24.8k
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 ...
Ash Machine's user avatar
  • 9,731
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',...
ʞɔıu's user avatar
  • 47.8k
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"); ...
Ahmed Nabil's user avatar
  • 18.1k
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?
Mirko Arcese's user avatar
  • 5,323
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]
ramesh.mimit's user avatar
  • 9,565
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?
Johanna's user avatar
  • 27.3k
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.
tunnuz's user avatar
  • 23.6k
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
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 ...
ldsenow's user avatar
  • 5,965
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 ...
JD Long's user avatar
  • 60.3k
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?
scatman's user avatar
  • 14.3k
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 ...
Sridhar Ratnakumar's user avatar
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 ...
SaaS Developer's user avatar
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 ...
AkshaiShah's user avatar
  • 5,809
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)) ...
elfuego1's user avatar
  • 10.3k
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); ...
Himanshu's user avatar
  • 4,821
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:...
Rajeev's user avatar
  • 45.9k
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 ...
Zack's user avatar
  • 13.6k
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 ...
user1909486's user avatar
  • 4,659
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 ...
Mr_Chimp's user avatar
  • 6,808
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, ...]...
layo's user avatar
  • 4,587
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 ...
Corey Goldberg's user avatar
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?
Jader Dias's user avatar
  • 89.3k
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]
Nope's user avatar
  • 35.4k
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?
user496949's user avatar
  • 84.7k
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]])...
user3132783's user avatar
  • 5,405
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 ...
ChangeMyName's user avatar
  • 7,228
423 votes
6 answers
631k views

Convert NumPy array to Python list

How do I convert a NumPy array into a Python List?
Alex Brooks's user avatar
  • 5,233
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 ...
James's user avatar
  • 4,217
416 votes
13 answers
589k views

Add list to set

How do I add a list of values to an existing set?
Adam Matan's user avatar
  • 132k
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' || ...
ErikE's user avatar
  • 49.6k
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 ...
Steven Jeuris's user avatar
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 =...
Mikhail M.'s user avatar
  • 5,808
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 ...
Mohamad Ibrahim's user avatar
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 ...
seler's user avatar
  • 8,973
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(",") >&...
user avatar
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 ...
Jonathan Livni's user avatar
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 ...
euphoria83's user avatar
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 ...
Cédric Boivin's user avatar
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[...
Luigi Plinge's user avatar
  • 50.9k
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 ...
Ernestas Gruodis's user avatar
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?
user219126's user avatar
  • 3,921
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 ...
Parand's user avatar
  • 104k
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 ...
Prasad's user avatar
  • 59.2k
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?
AlikElzin-kilaka's user avatar
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 ...
AKM's user avatar
  • 6,375
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)]
titus's user avatar
  • 5,644
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?
opensas's user avatar
  • 61.7k
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 ...
bgame2498's user avatar
  • 4,717