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,720
questions
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 = ...
5319
votes
32
answers
4.3m
views
How do I make a flat list out of a list of lists?
I have a list of lists like
[
[1, 2, 3],
[4, 5, 6],
[7],
[8, 9]
]
How can I flatten it to get [1, 2, 3, 4, 5, 6, 7, 8, 9]?
If your list of lists comes from a nested list ...
4388
votes
46
answers
6.3m
views
How to find the index for a given item in a list?
Given a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get its index 1?
3292
votes
24
answers
2.2m
views
How do I clone a list so that it doesn't change unexpectedly after assignment?
While using new_list = my_list, any modifications to new_list changes my_list every time. Why is this, and how can I clone or copy the list to prevent it?
3238
votes
31
answers
4.4m
views
How do I concatenate two lists in Python?
How do I concatenate two lists in Python?
Example:
listone = [1, 2, 3]
listtwo = [4, 5, 6]
Expected outcome:
>>> joinedlist
[1, 2, 3, 4, 5, 6]
3226
votes
27
answers
4.9m
views
How do I check if a list is empty?
For example, if passed the following:
a = []
How do I check to see if a is empty?
3115
votes
70
answers
1.7m
views
How do I split a list into equally-sized chunks?
How do I split a list of arbitrary length into equal sized chunks?
See also: How to iterate over a list in chunks.
To chunk strings, see Split string every nth character?.
3111
votes
20
answers
3.3m
views
What is the difference between Python's list methods append and extend?
What's the difference between the list methods append() and extend()?
2780
votes
22
answers
1.4m
views
How to sort a list of dictionaries by a value of the dictionary in Python?
How do I sort a list of dictionaries by a specific key's value? Given:
[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
When sorted by name, it should become:
[{'name': 'Bart', 'age': 10}, ...
2750
votes
26
answers
3.2m
views
How do I get the last element of a list?
How do I get the last element of a list? Which way is preferred?
alist[-1]
alist[len(alist) - 1]
2369
votes
18
answers
2.2m
views
How can I randomly select (choose) an item from a list (get a random element)?
How do I retrieve an item at random from the following list?
foo = ['a', 'b', 'c', 'd', 'e']
2266
votes
18
answers
4.1m
views
How to remove an element from a list by index
How do I remove an element from a list by index?
I found list.remove(), but this slowly scans the list for an item by value.
2266
votes
11
answers
3.8m
views
How do I get the number of elements in a list (length of a list) in Python?
How do I get the number of elements in the list items?
items = ["apple", "orange", "banana"]
# There are 3 items.
2160
votes
30
answers
2.9m
views
How do I count the occurrences of a list item?
Given a single item, how do I count occurrences of it in a list, in Python?
A related but different problem is counting occurrences of each different element in a collection, getting a dictionary or ...
2122
votes
26
answers
1.3m
views
How do I check if a variable is an array in JavaScript?
How do I check if a variable is an array in JavaScript?
if (variable.constructor == Array)
2095
votes
10
answers
1.5m
views
Why is it string.join(list) instead of list.join(string)?
This has always confused me. It seems like this would be nicer:
["Hello", "world"].join("-")
Than this:
"-".join(["Hello", "world"])
Is ...
1744
votes
22
answers
1.3m
views
Make a dictionary (dict) from separate lists of keys and values
I want to combine these:
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
into a single dictionary:
{'name': 'Monty', 'age': 42, 'food': 'spam'}
How can I do this?
1716
votes
29
answers
251k
views
Why not inherit from List<T>?
When planning out my programs, I often start with a chain of thought like so:
A football team is just a list of football players. Therefore, I should represent it with:
var football_team = new ...
1681
votes
13
answers
2.0m
views
if/else in a list comprehension
How do I convert the following for-loop containing an if/else into a list comprehension?
results = []
for x in xs:
results.append(f(x) if x is not None else '')
It should yield '' if x is None, ...
1636
votes
24
answers
1.8m
views
How to Sort a List<T> by a property in the object
I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a list of this Order class:
List<Order> objListOrder = new List<Order>();
...
1468
votes
58
answers
2.2m
views
Removing duplicates in lists
How can I check if a list has any duplicates and return a new list without duplicates?
1357
votes
37
answers
1.9m
views
How do I reverse a list or loop over it backwards?
How do I iterate over a list in reverse in Python?
See also: How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)?
1350
votes
25
answers
2.2m
views
Get a list from Pandas DataFrame column headers
I want to get a list of the column headers from a Pandas DataFrame. The DataFrame will come from user input, so I won't know how many columns there will be or what they will be called.
For example, ...
1298
votes
13
answers
2.0m
views
How do I return dictionary keys as a list in Python?
With Python 2.7, I can get dictionary keys, values, or items as a list:
>>> newdict = {1:0, 2:0, 3:0}
>>> newdict.keys()
[1, 2, 3]
With Python >= 3.3, I get:
>>> newdict....
1297
votes
25
answers
2.0m
views
Converting array to list in Java
How do I convert an array to a list in Java?
I used the Arrays.asList() but the behavior (and signature) somehow changed from Java SE 1.4.2 (docs now in archive) to 8 and most snippets I found on the ...
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 ...
1259
votes
12
answers
2.9m
views
Fastest way to check if a value exists in a list
What is the fastest way to check if a value exists in a very large list (with millions of values) and what its index is?
1242
votes
33
answers
1.5m
views
Get difference between two lists with Unique Entries
I have two lists in Python:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
Assuming the elements in each list are unique, I want to create a third list with items from the first list ...
1231
votes
10
answers
964k
views
How do I sort a list of objects based on an attribute of the objects?
I have a list of Python objects that I want to sort by a specific attribute of each object:
[Tag(name="toe", count=10), Tag(name="leg", count=2), ...]
How do I sort the list by ....
1206
votes
30
answers
2.8m
views
Get unique values from a list in python [duplicate]
I want to get the unique values from the following list:
['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
The output which I require is:
['nowplaying', 'PBS', 'job', '...
1201
votes
27
answers
2.0m
views
Is there a simple way to delete a list element by value?
I want to remove a value from a list if it exists in the list (which it may not).
a = [1, 2, 3, 4]
b = a.index(6)
del a[b]
print(a)
The above gives the error:
ValueError: list.index(x): x not in ...
1201
votes
15
answers
2.0m
views
Difference between del, remove, and pop on lists in Python
Is there any difference between these three methods to remove an element from a list in Python?
a = [1, 2, 3]
a.remove(2)
a # [1, 3]
a = [1, 2, 3]
del a[1]
a # [1, 3]
a = ...
1186
votes
3
answers
3.8m
views
How to convert list to string [duplicate]
How can I convert a list to a string using Python?
1174
votes
12
answers
2.2m
views
How to concatenate (join) items in a list to a single string
How do I concatenate a list of strings into a single string?
For example, given ['this', 'is', 'a', 'sentence'], how do I get "this-is-a-sentence"?
For handling a few strings in separate ...
1152
votes
22
answers
464k
views
What's the difference between lists and tuples?
What's the difference between tuples/lists and what are their advantages/disadvantages?
1125
votes
32
answers
678k
views
Randomize a List<T>
What is the best way to randomize the order of a generic list in C#? I've got a finite set of 75 numbers in a list I would like to assign a random order to, in order to draw them for a lottery type ...
1109
votes
18
answers
839k
views
List comprehension vs. lambda + filter
I have a list that I want to filter by an attribute of the items.
Which of the following is preferred (readability, performance, other reasons)?
xs = [x for x in xs if x.attribute == value]
xs = ...
1067
votes
33
answers
1.5m
views
How do I join two lists in Java?
Is there a simpler way than:
List<String> newList = new ArrayList<String>();
newList.addAll(listOne);
newList.addAll(listTwo);
Conditions:
Do not modify the original lists.
JDK only.
No ...
1057
votes
13
answers
1.3m
views
How do I remove the first item from a list?
How do I remove the first item from a list?
[0, 1, 2, 3] → [1, 2, 3]
1052
votes
31
answers
730k
views
How do I remove duplicates from a list, while preserving order?
How do I remove duplicates from a list, while preserving order? Using a set to remove duplicates destroys the original order.
Is there a built-in or a Pythonic idiom?
978
votes
14
answers
1.1m
views
Remove empty strings from a list of strings
I want to remove all empty strings from a list of strings in python.
My idea looks like this:
while '' in str_list:
str_list.remove('')
Is there any more pythonic way to do this?
971
votes
26
answers
2.3m
views
Writing a list to a file with Python, with newlines
How do I write a list to a file? writelines() doesn't insert newline characters, so I need to do:
f.writelines([f"{line}\n" for line in lines])
950
votes
19
answers
79k
views
List of lists changes reflected across sublists unexpectedly
I created a list of lists:
>>> xs = [[1] * 4] * 3
>>> print(xs)
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
Then, I changed one of the innermost values:
>>> xs[0][0] = 5
>...
934
votes
26
answers
1.1m
views
Shuffling a list of objects [duplicate]
How do I shuffle a list of objects? I tried random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
But it outputs:
None
932
votes
14
answers
3.2m
views
Find a value in a list [duplicate]
I use the following to check if item is in my_list:
if item in my_list:
print("Desired item is in list")
Is "if item in my_list:" the most "pythonic" way of finding ...
913
votes
25
answers
2.6m
views
How to make a new List in Java
We create a Set as:
Set myset = new HashSet()
How do we create a List in Java?
911
votes
11
answers
951k
views
How to sort a list/tuple of lists/tuples by the element at a given index
I have some data either in a list of lists or a list of tuples, like this:
data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]
And I want to sort by the 2nd element in the subset. ...
905
votes
30
answers
3.0m
views
How to define a two-dimensional array?
I want to define a two-dimensional array without an initialized length like this:
Matrix = [][]
But this gives an error:
IndexError: list index out of range
901
votes
18
answers
2.3m
views
Create an empty list with certain size in Python
How do I create an empty list that can hold 10 elements?
After that, I want to assign values in that list. For example:
xs = list()
for i in range(0, 9):
xs[i] = i
However, that gives IndexError: ...
892
votes
21
answers
723k
views
How to convert string representation of list to a list
I was wondering what the simplest way is to convert a string representation of a list like the following to a list:
x = '[ "A","B","C" , " D"]'
Even in cases ...