All Questions
3,890
questions
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?
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. ...
549
votes
9
answers
546k
views
Sort a list of tuples by 2nd item (integer value) [duplicate]
I have a list of tuples that looks something like this:
[('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
I want to sort this list in ascending order by the integer value inside the tuples. Is ...
540
votes
7
answers
470k
views
List vs tuple, when to use each? [duplicate]
In Python, when should you use lists and when tuples?
Sometimes you don't have a choice, for example if you have
"hello %s you are %s years old" % x
then x must be a tuple.
But if I am the one who ...
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 ...
366
votes
10
answers
371k
views
How to merge lists into a list of tuples?
What is the Pythonic approach to achieve the following?
# Original lists:
list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
# List of tuples from 'list_a' and 'list_b':
list_c = [(1,5), (2,6), (3,7), (4,...
321
votes
9
answers
141k
views
Are tuples more efficient than lists in Python?
Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements?
306
votes
2
answers
253k
views
How to unzip a list of tuples into individual lists? [duplicate]
I have a list of tuples l = [(1,2), (3,4), (8,9)]. How can I, succinctly and Pythonically, unzip this list into two independent lists, to get [ [1, 3, 8], [2, 4, 9] ]?
In other words, how do I get the ...
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)
...
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 ...
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']
243
votes
1
answer
96k
views
What is the inverse function of zip in python? [duplicate]
I've used the zip function from the Numpy library to sort tuples and now I have a list containing all the tuples. I had since modified that list and now I would like to restore the tuples so I can use ...
219
votes
7
answers
226k
views
What's the difference between lists enclosed by square brackets and parentheses in Python?
>>> x=[1,2]
>>> x[1]
2
>>> x=(1,2)
>>> x[1]
2
Are they both valid? Is one preferred for some reason?
213
votes
8
answers
44k
views
Why can tuples contain mutable items?
If a tuple is immutable then why can it contain mutable items?
It is seemingly a contradiction that when a mutable item such as a list does get modified, the tuple it belongs to maintains being ...
196
votes
10
answers
503k
views
Find an element in a list of tuples
I have a list 'a'
a= [(1,2),(1,4),(3,5),(5,7)]
I need to find all the tuples for a particular number. say for 1 it will be
result = [(1,2),(1,4)]
How do I do that?
170
votes
5
answers
161k
views
List of tuples to dictionary [duplicate]
Here's how I'm currently converting a list of tuples to dictionary in Python:
l = [('a',1),('b',2)]
h = {}
[h.update({k:v}) for k,v in l]
> [None, None]
h
> {'a': 1, 'b': 2}
Is there a better ...
164
votes
9
answers
474k
views
Explicitly select items from a list or tuple
I have the following Python list (can also be a tuple):
myList = ['foo', 'bar', 'baz', 'quux']
I can say
>>> myList[0:3]
['foo', 'bar', 'baz']
>>> myList[::2]
['foo', 'baz']
>&...
155
votes
7
answers
100k
views
How to convert list of tuples to multiple lists?
Suppose I have a list of tuples and I want to convert to multiple lists.
For example, the list of tuples is
[(1,2),(3,4),(5,6),]
Is there any built-in function in Python that convert it to:
[1,3,...
154
votes
8
answers
238k
views
How to extract the n-th elements from a list of tuples
I'm trying to obtain the n-th elements from a list of tuples.
I have something like:
elements = [(1,1,1),(2,3,7),(3,5,10)]
I wish to extract only the second elements of each tuple into a list:
...
145
votes
7
answers
210k
views
Python : List of dict, if exists increment a dict value, if not append a new dict
I would like do something like that.
list_of_urls = ['http://www.google.fr/', 'http://www.google.fr/',
'http://www.google.cn/', 'http://www.google.com/',
'http://www....
140
votes
11
answers
172k
views
Why can't I use a list as a dict key in python? Exactly what can and cannot be used, and why?
I found that the following are all valid:
>>> d = {}
>>> d[None] = 'foo'
>>> d[(1, 3)] = 'baz'
Even a module can be used as a dict key:
>>> import sys
>>> ...
138
votes
3
answers
174k
views
How to find the maximum value in a list of tuples? [duplicate]
I have a list with ~10^6 tuples in it like this:
[(101, 153), (255, 827), (361, 961), ...]
^ ^
X Y
I want to find the maximum value of the Ys in this list, but also want to know the X ...
132
votes
9
answers
111k
views
Does Python have an immutable list?
Does python have immutable lists?
Suppose I wish to have the functionality of an ordered collection of elements, but which I want to guarantee will not change, how can this be implemented? Lists are ...
128
votes
4
answers
29k
views
Why do tuples take less space in memory than lists?
A tuple takes less memory space in Python:
>>> a = (1,2,3)
>>> a.__sizeof__()
48
whereas lists takes more memory space:
>>> b = [1,2,3]
>>> b.__sizeof__()
64
...
113
votes
16
answers
243k
views
Subtracting 2 lists in Python
Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like
[2,2,2] - [1,1,1] = [1,1,1]
Should I use tuples?
If none of them defines these ...
113
votes
11
answers
82k
views
Transform "list of tuples" into a flat list or a matrix
With Sqlite, a select .. from command returns the results output, which prints:
>>print output
[(12.2817, 12.2817), (0, 0), (8.52, 8.52)]
It seems to be a list of tuples. I would like to either ...
108
votes
13
answers
117k
views
In what case would I use a tuple as a dictionary key? [closed]
I was studying the difference between lists and tuples (in Python). An obvious one is that tuples are immutable (the values cannot be changed after initial assignment), while lists are mutable.
A ...
103
votes
8
answers
143k
views
How to search a list of tuples in Python
So I have a list of tuples such as this:
[(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
I want this list for a tuple whose number value is equal to something.
So that if I do search(53) it ...
101
votes
8
answers
51k
views
Why is tuple faster than list in Python?
I've just read in "Dive into Python" that "tuples are faster than lists".
Tuple is immutable, and list is mutable, but I don't quite understand why tuple is faster.
Anyone did a performance test on ...
97
votes
6
answers
163k
views
Accessing a value in a tuple that is in a list
[(1,2), (2,3), (4,5), (3,4), (6,7), (6,7), (3,8)]
How do I return the 2nd value from each tuple inside this list?
Desired output:
[2, 3, 5, 4, 7, 7, 8]
96
votes
14
answers
82k
views
Convert a Scala list to a tuple?
How can I convert a list with (say) 3 elements into a tuple of size 3?
For example, let's say I have val x = List(1, 2, 3) and I want to convert this into (1, 2, 3). How can I do this?
90
votes
1
answer
108k
views
List of Tuples to DataFrame Conversion [duplicate]
I have a list of tuples similar to the below:
[(date1, ticker1, value1),(date1, ticker1, value2),(date1, ticker1, value3)]
I want to convert this to a DataFrame with index=date1, columns=ticker1, ...
78
votes
7
answers
6k
views
Why does b+=(4,) work and b = b + (4,) doesn't work when b is a list?
If we take b = [1,2,3] and if we try doing: b+=(4,)
It returns b = [1,2,3,4], but if we try doing b = b + (4,) it doesn't work.
b = [1,2,3]
b+=(4,) # Prints out b = [1,2,3,4]
b = b + (4,) # Gives ...
77
votes
5
answers
306k
views
Append a tuple to a list - what's the difference between two ways?
I wrote my first "Hello World" 4 months ago. Since then, I have been following a Coursera Python course provided by Rice University. I recently worked on a mini-project involving tuples and lists. ...
72
votes
13
answers
234k
views
Using Python's list index() method on a list of tuples or objects?
Python's list type has an index() method that takes one parameter and returns the index of the first item in the list matching the parameter. For instance:
>>> some_list = ["apple", "pear", ...
71
votes
7
answers
3k
views
Why does splatting create a tuple on the rhs but a list on the lhs?
Consider, for example,
squares = *map((2).__rpow__, range(5)),
squares
# (0, 1, 4, 9, 16)
*squares, = map((2).__rpow__, range(5))
squares
# [0, 1, 4, 9, 16]
So, all else being equal we get a list ...
66
votes
7
answers
47k
views
How to convert a list to a list of tuples?
I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.
This is the input list:
L = [1,term1, 3, term2, x, term3,... z, termN]
...
62
votes
3
answers
81k
views
Add all elements of an iterable to list
Is there a more concise way of doing the following?
t = (1,2,3)
t2 = (4,5)
l.addAll(t)
l.addAll(t2)
print l # [1,2,3,4,5]
This is what I have tried so far: I would prefer to avoid passing in the ...
61
votes
9
answers
198k
views
Converting string to tuple without splitting characters
I am striving to convert a string to a tuple without splitting the characters of the string in the process. Can somebody suggest an easy method to do this. Need a one liner.
Fails
a = 'Quattro ...
60
votes
18
answers
18k
views
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
In many places, (1,2,3) (a tuple) and [1,2,3] (a list) can be used interchangeably.
When should I use one or the other, and why?
57
votes
4
answers
158k
views
Select value from list of tuples where condition
I have a list of tuples. Every tuple has 5 elements (corresponding to 5 database columns) and I'd like to make a query
select attribute1 from mylist where attribute2 = something
e.g.
personAge = ...
56
votes
3
answers
52k
views
Changing values of a list of namedtuples
I have a list of namedtuples named Books and am trying to increase the price field by 20% which does change the value of Books. I tried to do:
from collections import namedtuple
Book = namedtuple('...
54
votes
6
answers
31k
views
List unhashable, but tuple hashable?
In How to hash lists? I was told that I should convert to a tuple first, e.g. [1,2,3,4,5] to (1,2,3,4,5).
So the first cannot be hashed, but the second can. Why*?
*I am not really looking for a ...
46
votes
7
answers
74k
views
How do I sum the first value in each tuple in a list of tuples in Python?
I have a list of tuples (always pairs) like this:
[(0, 1), (2, 3), (5, 7), (2, 1)]
I'd like to find the sum of the first items in each pair, i.e.:
0 + 2 + 5 + 2
How can I do this in Python? At the ...
46
votes
2
answers
36k
views
Are there any methods included in Scala to convert tuples to lists?
I have a Tuple2 of List[List[String]] and I'd like to be able to convert the tuple to a list so that I can then use List.transpose(). Is there any way to do this? Also, I know it's a Pair, though I'm ...
46
votes
1
answer
14k
views
Python: Unpacking an inner nested tuple/list while still getting its index number
I am familiar with using enumerate():
>>> seq_flat = ('A', 'B', 'C')
>>> for num, entry in enumerate(seq_flat):
print num, entry
0 A
1 B
2 C
I want to be able to do the ...
44
votes
6
answers
179k
views
How can I access each element of a pair in a pair list?
I have a list called pairs.
pairs = [("a", 1), ("b", 2), ("c", 3)]
And I can access elements as:
for x in pairs:
print x
which gives output like:
('a', 1) ('b', 2) ('c', 3)
But I want to ...
43
votes
5
answers
25k
views
Converting a list of tuples into a dict
I have a list of tuples like this:
[
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
I want to iterate through this keying by the first item, so, for example, I could print something ...
43
votes
3
answers
129k
views
python: create list of tuples from lists [duplicate]
I have two lists:
x = ['1', '2', '3']
y = ['a', 'b', 'c']
and I need to create a list of tuples from these lists, as follows:
z = [('1','a'), ('2','b'), ('3','c')]
I tried doing it like this:
z = ...
41
votes
4
answers
35k
views
How to convert nested list of lists into a list of tuples in python 3.3?
I am trying to convert a nested list of lists into a list of tuples in Python 3.3. However, it seems that I don't have the logic to do that.
The input looks as below:
>>> nested_lst = [['...