All Questions
Tagged with list python-2.7
2,997
questions
188
votes
9
answers
571k
views
Zip lists in Python
I am trying to learn how to "zip" lists. To this end, I have a program, where at a particular point, I do the following:
x1, x2, x3 = stuff.calculations(withdataa)
This gives me three lists, x1, x2, ...
179
votes
6
answers
363k
views
Insert an element at a specific index in a list and return the updated list
I have this:
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> print a.insert(2, 3)
None
>>> print a
[1, 2, 3, 4]
>>> b = a.insert(3, 6)
>>> print b
...
134
votes
4
answers
244k
views
python filter list of dictionaries based on key value
I have a list of dictionaries and each dictionary has a key of (let's say) 'type' which can have values of 'type1', 'type2', etc. My goal is to filter out these dictionaries into a list of the same ...
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
...
119
votes
7
answers
214k
views
The most efficient way to remove first N elements in a list?
I need to remove the first n elements from a list of objects in Python 2.7. Is there an easy way, without using loops?
108
votes
2
answers
174k
views
How to get everything from the list except the first element using list slicing [duplicate]
So I have something that I am parsing, however here is an example of what I would like to do:
list = ['A', 'B', 'C']
And using list slicing have it return to me everything but the first index. So in ...
99
votes
10
answers
401k
views
Find empty or NaN entry in Pandas Dataframe
I am trying to search through a Pandas Dataframe to find where it has a missing entry or a NaN entry.
Here is a dataframe that I am working with:
cl_id a c d e ...
98
votes
8
answers
150k
views
How to join entries in a set into one string?
Basically, I am trying to join together the entries in a set in order to output one string. I am trying to use syntax similar to the join function for lists. Here is my attempt:
list = ["gathi-109","...
92
votes
2
answers
53k
views
Why is a list comprehension so much faster than appending to a list?
I was wondering why list comprehension is so much faster than appending to a list. I thought the difference is just expressive, but it's not.
>>> import timeit
>>> timeit.timeit(...
75
votes
5
answers
174k
views
Remove list from list in Python [duplicate]
Possible Duplicate:
Get difference from two lists in Python
What is a simplified way of doing this? I have been trying on my own, and I can't figure it out.
list a and list b, the new list should ...
62
votes
7
answers
86k
views
How to check if key exists in list of dicts in python?
Say I have a list of dicts that looks like this:
[{1: "a"}, {2: "b"}]
What is the pythonic way to indicate if a certain key is in one of the dicts in the list?
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 ...
58
votes
3
answers
73k
views
List comprehension list of lists
I have a list of lists, and would like to use list comprehension to apply a function to each element in the list of lists, but when I do this, I end up with one long list rather than my list of lists.
...
55
votes
8
answers
122k
views
Getting a sublist of a Python list, with the given indices?
I have a Python list, say a = [0,1,2,3,4,5,6]. I also have a list of indices, say b = [0,2,4,5]. How can I get the list of elements of a with indices in b?
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 ...
51
votes
2
answers
68k
views
Return a variable in a Python list with double quotes instead of single
I am trying to return a variable from a list of strings in double quotes rather than single.
For example, if my list is
List = ["A", "B"]
if I type List[0] the output is 'A'. Rather, I want "A". ...
45
votes
3
answers
131k
views
Write and read a list from file
This is a slightly weird request but I am looking for a way to write a list to file and then read it back some other time.
I have no way to remake the lists so that they are correctly formed/...
40
votes
4
answers
227k
views
TypeError: unsupported operand type(s) for -: 'list' and 'list'
I am trying to implement the Naive Gauss and getting the unsupported operand type error on execution.
Output:
execfile(filename, namespace)
File "/media/zax/MYLINUXLIVE/A0N-.py", line 26, in <...
40
votes
5
answers
32k
views
Sort a list with a custom order in Python
I have a list
mylist = [['123', 'BOOL', '234'], ['345', 'INT', '456'], ['567', 'DINT', '678']]
I want to sort it with the order of 1. DINT 2. INT 3. BOOL
Result:
[['567', 'DINT', '678'], ['345', '...
39
votes
2
answers
39k
views
How to sort list of lists according to length of sublists [duplicate]
I have the following list
a = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h'], ['i', 'j', 'k', 'l'], ['m', 'n'], ['o']]
I would like to sort the list based on the length of their sub lists.
The ...
37
votes
4
answers
150k
views
How to check if a specific integer is in a list
I want to know how to make an if statement that executes a clause if a certain integer is in a list.
All the other answers I've seen ask for a specific condition like prime numbers, duplicates, etc. ...
35
votes
2
answers
18k
views
Efficiently filtering out 'None' items in a list comprehension in which a function is called
I have a list comprehension that calls a function which potentially returns None.
f = lambda x: x if x < 3 else None
l = [f(x) for x in [1,2,3,4]] # [1, 2, None, None]
I'd like to have the list ...
35
votes
3
answers
42k
views
sum each value in a list of tuples
I have a list of tuples similar to this:
l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]
I want to create a simple one-liner that will give me the following result:
r = (25, 20) or r = [25, 20] # don'...
35
votes
3
answers
46k
views
How to have a set of sets in Python? [duplicate]
In Python there's no full support for heterogeneous data structures. For example this fails:
set(set(1,2),set(2,3))
What's the best way to treat sets of sets?
30
votes
3
answers
101k
views
Check if a key exists in a Python list
Suppose I have a list that can have either one or two elements:
mylist=["important", "comment"]
or
mylist=["important"]
Then I want to have a variable to work as a flag depending on this 2nd value ...
29
votes
7
answers
29k
views
finding duplicates in a list of lists
I am using Python 2.7 and am trying to de-duplicate a list of lists and merge the values of the duplicates.
Right now I have:
original_list = [['a', 1], ['b', 1], ['a', 1], ['b', 1], ['b', 2], ['c', ...
28
votes
6
answers
31k
views
What is the difference between list and iterator in Python? [closed]
I am reading the book Think Python: How to think like a computer scientist, which says that in Python 3.x, dict([list of tuples]) returns an iterator instead of a list (as is the case in Python 2.7).
...
27
votes
1
answer
66k
views
Python iterate over two lists simultaneously [duplicate]
Is there a way in python to forloop over two or more lists simultaneously?
Something like
a = [1,2,3]
b = [4,5,6]
for x,y in a,b:
print x,y
to output
1 4
2 5
3 6
I know that I can do it with ...
27
votes
4
answers
16k
views
How does the min/max function on a nested list work?
Lets say, there is a nested list, like:
my_list = [[1, 2, 21], [1, 3], [1, 2]]
When the function min() is called on this:
min(my_list)
The output received is
[1, 2]
Why and How does it work? ...
26
votes
9
answers
97k
views
Get max value from a list with lists?
So I have a list that contains several list which all have three strings first, then one float number, like:
resultlist = [["1", "1", "a", 8.3931], ["1", "2", "b", 6.3231], ["2", "1", "c", 9.1931]]
...
25
votes
2
answers
56k
views
XOR on two lists in Python [duplicate]
I'm a beginner in Python, and I have to do the XOR between two lists (the first one with the length : 600 and the other 60)
I really don't know how to do that, if somebody can explain me how, it will ...
25
votes
3
answers
36k
views
Skip elements on a condition based in a list comprehension in python
I have a list List:
List = [-2,9,4,-6,7,0,1,-4]
For numbers less than zero (0) in the list , I would like to skip those numbers and form another list.
Example:-
List = [9,4,7,0,1]
This is a kind ...
24
votes
2
answers
45k
views
Splitting a list in a Pandas cell into multiple columns [duplicate]
I have a really simple Pandas dataframe where each cell contains a list. I'd like to split each element of the list into it's own column. I can do that by exporting the values and then creating a new ...
23
votes
3
answers
26k
views
Generate list of numbers in specific format
I need to generate a list of numbers in a specific format. The format is
mylist = [00,01,02,03,04,05,06,07,08,09,10,11,12,13,14,15]
#Numbers between 0-9 are preceded by a zero.
I know how to ...
22
votes
5
answers
12k
views
Python: How RECURSIVELY remove None values from a NESTED data structure (lists and dictionaries)?
Here is some nested data, that includes lists, tuples, and dictionaries:
data1 = ( 501, (None, 999), None, (None), 504 )
data2 = { 1:601, 2:None, None:603, 'four':'sixty' }
data3 = OrderedDict( [(...
22
votes
1
answer
12k
views
Should I use a Python deque or list as a stack? [duplicate]
I want a Python object that I can use as a stack. Is it better to use a deque or a list and does it make a difference whether I have a small number of elements or a large number of elements?
22
votes
5
answers
23k
views
How to slice a list of tuples in python?
Assuming:
L = [(0,'a'), (1,'b'), (2,'c')]
How to get the index 0 of each tuple as the pretended result:
[0, 1, 2]
To get that I used python list comprehension and solved the problem:
[num[0] for ...
21
votes
3
answers
21k
views
Using Counter with list of lists
How would I use the Counter in the collections library to convert a list of lists into a count of the number of times each word occurs overall?
E.g. [['a','b','a','c'], ['a','b','c','d']] -> {a:2,...
21
votes
8
answers
7k
views
Constructing the largest number possible by rearranging a list
Say I have an array of positive whole integers; I'd like to manipulate the order so that the concatenation of the resultant array is the largest number possible. For example [97, 9, 13] results in ...
19
votes
6
answers
41k
views
Remove tuple from list of tuples if certain condition is met
I have a list of tuples that look like this;
ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD')]
I want to remove the tuples when the first element of the tuple is less than 50. The ...
19
votes
4
answers
39k
views
How to determined if a 2 dimensional list contain a value?
I have a list like following
mylist = [('value1', 'value2', 'value3'), ('secval1', 'secval2', 'secval3')]
how do I see if the list contains 'value2'?
19
votes
3
answers
2k
views
Optimize the performance of dictionary membership for a list of Keys
I am trying to write a code which should return true if any element of list is present in a dictionary. Performance of this piece is really important. I know I can just loop over list and break if I ...
19
votes
13
answers
99k
views
Python 2.7 creating a multidimensional list
In Python I want an intuitive way to create a 3 dimensional list.
I want an (n by n) list. So for n = 4 it should be:
x = [[[],[],[],[]],[[],[],[],[]],[[],[],[],[]],[[],[],[],[]]]
I've tried using:...
18
votes
10
answers
33k
views
Iterate every 2 elements from list at a time
Having list as ,
l = [1,2,3,4,5,6,7,8,9,0]
How can i iterate every two elements at a time ?
I am trying this ,
for v, w in zip(l[:-1],l[1:]):
print [v, w]
and getting output is like ,
[1, ...
18
votes
2
answers
6k
views
Sort a list of lists by length and value in Python
How can I sort a Python list (with sublists)? For example, I have the following list:
list1 = [[0, 4, 1, 5], [3, 1, 5], [4, 0, 1, 5]]
After sorting I am expecting:
list1 = [[3, 1, 5], [0, 4, 1, 5], ...
18
votes
4
answers
43k
views
Unittest - Assert a set of items of a list are (or not) contained in another list
Hello I am new to programming and and trying to make a test that checks whether any items in a list of items are present in another list (using unittest in Python 2.7).
For example if I have a list ["...
18
votes
3
answers
38k
views
Python - set list range to a specific value
I need to set a subset of a list to a specific value based on a tuple with bounds (start,end).
Currently I'm doing this:
indexes = range(bounds[0], bounds[1] + 1)
for i in indexes:
my_list[i] = '...
17
votes
7
answers
5k
views
Padding or truncating a Python list
I'd like to truncate or pad a list. E.g. for size 4:
[1,2,3] -> [1,2,3,0]
[1,2,3,4,5] -> [1,2,3,4]
I can see a couple of ways:
def trp(l, n):
""" Truncate or pad a list """
r = l[:n]
...
17
votes
6
answers
16k
views
flatten list of list through list comprehension
I am trying to flatten a list using list comprehension in python. My list is somewhat like
[[1, 2, 3], [4, 5, 6], 7, 8]
just for printing then individual item in this list of list I wrote this ...
17
votes
5
answers
19k
views
List on python appending always the same value [duplicate]
I have the following code inside a while loop.
if gender == 0 and len(men) < 51 :
height = float((random.uniform(1.3, 1.9) + (random.randint(10, 20)/100.)).__format__('.2f'))
weight = ...