Skip to content

Tag: list

Python ‘list indices must be integers, not tuple”

I have been banging my head against this for two days now. I am new to python and programming so the other examples of this type of error have not helped me to much. I am reading through the documentation for lists and tuples, but haven’t found anything that helps. Any pointer would be much appreciated.…

Assign a value to a list of variables using a loop

I can do this in C, but I haven’t come across it in Python. Say I have a few variables: and I have list of values [1, 2, 3, 4] how can I assign the values to the variables with a single loop so I get the following result: Answer While you technically can modify local variables, doing so is

Explanation of how nested list comprehension works?

I have no problem understanding this: I thought that was all, but then I found this snippet: Which makes b = [1,2,3,4,5,6]. The problem is I’m having trouble understanding the syntax in [x for xs in a for x in xs], Could anyone explain how it works? Answer Ah, the incomprehensible “nested” c…

Index all *except* one item in python

Is there a simple way to index all elements of a list (or array, or whatever) except for a particular index? E.g., mylist[3] will return the item in position 3 milist[~3] will return the whole list except for 3 Answer For a list, you could use a list comp. For example, to make b a copy of a without the

Find matching values in a list of lists

I’m trying to iterate over a list of lists in python 2.7.5 and return those where the first value is found in a second list, something like this: So I would want list3 to contain [[‘aa’,1,3,7],[‘bc’, 3, 4, 4]] but instead I just get the whole of list2. Answer Try a more simple ap…