All Questions

Tagged with
Filter by
Sorted by
Tagged with
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....
user avatar
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....
mozami's user avatar
  • 7,461
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]. ...
hoang tran's user avatar
  • 3,978
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(...
Boathouse's user avatar
  • 2,735
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?
lemiant's user avatar
  • 4,295
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&...
Jiew Meng's user avatar
  • 85.8k
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 ...
Michael Murphy's user avatar
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 ...
Stefan Pochmann's user avatar
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 ...
Prasad's user avatar
  • 6,024
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?
RedVelvet's user avatar
  • 1,783
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 ...
linello's user avatar
  • 8,552
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 ...
Edamame's user avatar
  • 24.6k
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 ...
Omid CompSCI's user avatar
  • 1,891
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() ...
Rex's user avatar
  • 1,211
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] ...
Sarfaraz Nawaz's user avatar
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 ...
user3088605's user avatar
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 ...
halex's user avatar
  • 16.3k
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?
yezi3's user avatar
  • 973
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(...
rafaelc's user avatar
  • 58.6k
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 ...
Supun Dasantha Kuruppu's user avatar
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 ...
Paul Panzer's user avatar
  • 52.6k
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) ...
Michal's user avatar
  • 1,300
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 ...
Shankar's user avatar
  • 3,576
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 ...
Ravit's user avatar
  • 1,502
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 ...
user avatar
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('...
Leon Surrao's user avatar
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 ...
Tapojyoti Mandal's user avatar
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 ...
zegkljan's user avatar
  • 8,191
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 ...
ywat's user avatar
  • 2,837
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(). ...
Michael's user avatar
  • 7,607
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 ...
ThatsOkay's user avatar
  • 513
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): ...
yuenster's user avatar
  • 513
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 ...
nedla2004's user avatar
  • 1,145
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')...
Mulan's user avatar
  • 132k
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)...
Perspicacious's user avatar
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-...
James Reid's user avatar
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 ...
physics_researcher's user avatar
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 ...
zardav's user avatar
  • 1,180
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 = [...
user avatar
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 ...
Dahaka's user avatar
  • 305
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'), ([...
oarfish's user avatar
  • 4,348
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 ...
Matthieu Riegler's user avatar
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). ...
Abhishek Mishra's user avatar
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 ...
Firnagzen's user avatar
  • 1,252
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'] + ...
nwly's user avatar
  • 1,422
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 = [ ['...
qwertylpc's user avatar
  • 2,036
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 ...
Abid Rizvi's user avatar
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) ...
Cajuu''s user avatar
  • 1,154
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 = "" ...
Leonora Tindall's user avatar
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 = [] ...
jef's user avatar
  • 3,959

1
2 3 4 5
280