All Questions
Tagged with list python-3.x
13,985
questions
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....
644
votes
11
answers
628k
views
Getting a map() to return a list in Python 3.x [duplicate]
I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:
A: Python 2.6:
>>> map(chr, [66, 53, 0, 94])
['B', '5', '\x00', '^']
However, in Python 3....
343
votes
11
answers
426k
views
Access multiple elements of list knowing their index [duplicate]
I need to choose some elements from the given list, knowing their index. Let say I would like to create a new list, which contains element with index 1, 2, 5, from given list [-2, 1, 5, 3, 8, 5, 6]. ...
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(...
220
votes
4
answers
156k
views
Are lists thread-safe?
I notice that it is often suggested to use queues with multiple threads, instead of lists and .pop(). Is this because lists are not thread-safe, or for some other reason?
158
votes
3
answers
129k
views
Check if list of objects contain an object with a certain attribute value
I want to check if my list of objects contain an object with a certain attribute value.
class Test:
def __init__(self, name):
self.name = name
# in main()
l = []
l.append(Test("t1&...
153
votes
3
answers
402k
views
Appending to list in Python dictionary [duplicate]
Is there a more elegant way to write this code?
What I am doing: I have keys and dates. There can be a number of dates assigned to a key and so I am creating a dictionary of lists of dates to ...
149
votes
3
answers
6k
views
What causes [*a] to overallocate?
Apparently list(a) doesn't overallocate, [x for x in a] overallocates at some points, and [*a] overallocates all the time?
Here are sizes n from 0 to 12 and the resulting sizes in bytes for the three ...
131
votes
2
answers
148k
views
Calling filter returns <filter object at ... > [duplicate]
I am learning the concept of filters in Python. I am running a simple code like this.
>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
But instead of ...
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?
113
votes
11
answers
129k
views
Check if all elements of a list are of the same type
How can I check if the elements of a list are of the same type, without checking individually every element if possible?
For example, I would like to have a function to check that every element of ...
112
votes
7
answers
239k
views
Python: create a pandas data frame from a list
I am using the following code to create a data frame from a list:
test_list = ['a','b','c','d']
df_test = pd.DataFrame.from_records(test_list, columns=['my_letters'])
df_test
The above code works ...
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 ...
108
votes
2
answers
395k
views
Python, TypeError: unhashable type: 'list'
I'm receiving the following error in my program. The traceback:
Traceback (most recent call last):
File "C:\Python33\Archive\PythonGrafos\Alpha.py", line 126, in <module>
menugrafos()
...
105
votes
5
answers
134k
views
One liner: creating a dictionary from list with indices as keys
I want to create a dictionary out of a given list, in just one line. The keys of the dictionary will be indices, and values will be the elements of the list. Something like this:
a = [51,27,13,56] ...
94
votes
15
answers
288k
views
Count frequency of words in a list and sort by frequency
I am using Python 3.3
I need to create two lists, one for the unique words and the other for the frequencies of the word.
I have to sort the unique word list based on the frequencies list so that ...
93
votes
4
answers
106k
views
Size of a Python list in memory
I just experimented with the size of python data structures in memory. I wrote the following snippet:
import sys
lst1=[]
lst1.append(1)
lst2=[1]
print(sys.getsizeof(lst1), sys.getsizeof(lst2))
I got ...
93
votes
8
answers
345k
views
How can I generate a list of consecutive numbers? [duplicate]
Say if you had a number input 8 in python and you wanted to generate a list of consecutive numbers up to 8 like
[0, 1, 2, 3, 4, 5, 6, 7, 8]
How could you do this?
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(...
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 ...
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 ...
67
votes
3
answers
149k
views
Python range() and zip() object type
I understand how functions like range() and zip() can be used in a for loop. However I expected range() to output a list - much like seq in the unix shell. If I run the following code:
a=range(10)
...
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
1
answer
33k
views
How can I find the union on a list of sets in Python? [duplicate]
This is the input:
x = [{1, 2, 3}, {2, 3, 4}, {3, 4, 5}]
and the output should be:
{1, 2, 3, 4, 5}
I tried to use set().union(x) but this is the error I'm getting:
Traceback (most recent call ...
58
votes
2
answers
372k
views
Unsupported operand type(s) for +: 'int' and 'str' [duplicate]
I am currently learning Python so I have no idea what is going on.
num1 = int(input("What is your first number? "))
num2 = int(input("What is your second number? "))
num3 = int(input("What is your ...
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('...
56
votes
7
answers
69k
views
Union of multiple sets in python
[[1, '34', '44'], [1, '40', '30', '41'], [1, '41', '40', '42'], [1, '42', '41', '43'], [1, '43', '42', '44'], [1, '44', '34', '43']]
I have a list of lists. My aim is to check whether any one sublist ...
56
votes
9
answers
42k
views
zip list with a single element
I have a list of some elements, e.g. [1, 2, 3, 4] and a single object, e.g. 'a'. I want to produce a list of tuples with the elements of the list in the first position and the single object in the ...
56
votes
2
answers
36k
views
How to extend/concatenate two iterators in Python [duplicate]
I want concatenate two iterators in an efficient way.
Suppose we have two iterators (in Python3)
l1 = range(10) # iterator over 0, 1, ..., 9
l2 = range(10, 20) # iterator over 10, 11, ..., 19
...
56
votes
5
answers
27k
views
Let a class behave like it's a list in Python
I have a class which is essentially a collection/list of things. But I want to add some extra functions to this list. What I would like, is the following:
I have an instance li = MyFancyList(). ...
51
votes
2
answers
157k
views
I want to replace single quotes with double quotes in a list
So I am making a program that takes a text file, breaks it into words, then writes the list to a new text file.
The issue I am having is I need the strings in the list to be with double quotes not ...
51
votes
4
answers
75k
views
"TypeError: 'type' object is not subscriptable" in a function signature
Why am I receiving this error when I run this code?
Traceback (most recent call last): ...
46
votes
6
answers
129k
views
Detect If Item is the Last in a List [duplicate]
I am using Python 3, and trying to detect if an item is the last in a list, but sometimes there will repeats. This is my code:
a = ['hello', 9, 3.14, 9]
for item in a:
print(item, end='')
if ...
39
votes
5
answers
23k
views
How to chunk a list in Python 3?
I found the following code that is compatible with python2
from itertools import izip_longest
def grouper(n, iterable, padvalue=None):
"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f')...
38
votes
1
answer
1k
views
Concatenation using the + and += operators in Python [duplicate]
Recently, I have noticed an inconsistency while concatenating lists.
So if I use the + operator, it doesn't concatenates list with any object of different type. For example,
l = [1,2,3]
l = l + (4,5)...
37
votes
2
answers
133k
views
'dict' object has no attribute 'id'
This is my code. I'm trying to translate xml string into python list to be shown in html template.
self.task_xml = "<?xml version="1.0" encoding="utf-8"?>
<django-...
36
votes
1
answer
24k
views
Static typing in python3: list vs List [duplicate]
What is the difference between using list and List when defining for example the argument of a function in python3? For example, what is the difference between
def do_something(vars: list):
and
...
32
votes
4
answers
25k
views
Iterating over two lists one after another
I have two lists list1 and list2 of numbers, and I want to iterate over them with the same instructions. Like this:
for item in list1:
print(item.amount)
print(item.total_amount)
for item in ...
31
votes
6
answers
6k
views
Create a list of tuples with adjacent list elements if a condition is true
I am trying to create a list of tuples where the tuple contents are the number 9 and the number before it in the list.
Input List:
myList = [1, 8, 9, 2, 4, 9, 6, 7, 9, 8]
Desired Output:
sets = [...
30
votes
7
answers
115k
views
TypeError: list indices must be integers, not float
I have a python 3.x program that is producing an error:
def main():
names = ['Ava Fischer', 'Bob White', 'Chris Rich', 'Danielle Porter',
'Gordon Pike', 'Hannah Beauregard', 'Matt ...
29
votes
9
answers
4k
views
What is a Pythonic way of doing the following transformation on a list of dicts?
I have a list of dicts like this:
l = [{'name': 'foo', 'values': [1,2,3,4]}, {'name': 'bar', 'values': [5,6,7,8]}]
and I would like to obtain an output of this form:
>>> [('foo', 'bar'), ([...
29
votes
3
answers
40k
views
How to make a custom object iterable?
I have a list of custom-class objects (sample is below).
Using: list(itertools.chain.from_iterable(myBigList)) I wanted to "merge" all of the stations sublists into one big list. So I thought I need ...
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).
...
28
votes
9
answers
12k
views
Pythonic way to merge two overlapping lists, preserving order
Alright, so I have two lists, as such:
They can and will have overlapping items, for example, [1, 2, 3, 4, 5], [4, 5, 6, 7].
There will not be additional items in the overlap, for example, this will ...
27
votes
5
answers
29k
views
Concatenating dict values, which are lists
Suppose I have the following dict object:
test = {}
test['tree'] = ['maple', 'evergreen']
test['flower'] = ['sunflower']
test['pets'] = ['dog', 'cat']
Now, if I run test['tree'] + test['flower'] + ...
27
votes
2
answers
68k
views
Nested List to Pandas Dataframe with headers
Basically I am trying to do the opposite of How to generate a list from a pandas DataFrame with the column name and column values?
To borrow that example, I want to go from the form:
data = [
['...
26
votes
2
answers
7k
views
Is removing an element from the front of a list cheap in Python?
I am writing a program, that does a lot of deletions at either the front or back of a list of data, never the middle.
I understand that deletion of the last element is cheap, but how about deletion ...
26
votes
3
answers
5k
views
How does str.startswith really work?
I've been playing for a bit with startswith() and I've discovered something interesting:
>>> tup = ('1', '2', '3')
>>> lis = ['1', '2', '3', '4']
>>> '1'.startswith(tup)
...
26
votes
2
answers
39k
views
How can I use str.join() instead of "+=" to join a list of strings with separator?
I have some code which is essentially this:
data = ["some", "data", "lots", "of", "strings"]
separator = "."
output_string = ""
...
26
votes
6
answers
9k
views
How to split a list-of-strings into sublists-of-strings by a specific string element
I have a word list like below. I want to split the list by .. Is there any better or useful code in Python 3?
a = ['this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.']
result = []
...