List append in a "for" loop - python

I am trying to get a list of elements using a for loop to index my previous list. Here's the code:
for index in range(1,810):
list.extend(t[index])
list.extend(t[index+1])
list.extend(t[index])
I already have a list named "list" and t is an other list.
To be more specific I want to make my list like this.
t1,t2,t1,t2,t3,t2,t3,t4 etc.
I get this error TypeError: 'float' object is not iterable.

You should be using list.append since list.extend works on iterables; i.e. you can do stuff like lst=[1,2,3];lst.extend([4,5]) which would give you [1,2,3,4,5]
see this link if you want to read more

The other answers suggesting you use append fix your issue, but appending is very inefficient. You should use a list comprehension. Also, "list" is a keyword, so you should use another name.
my_list = [item for index in range(1,810) for item in [t[index],t[index+1],t[index]] ]

Related

Apply a function to every item in a list

I have the following code for pygame but it applies generally to python
expl_sounds = []
for snd in ['expl3.wav', 'expl6.wav']:
expl_sounds.append(pygame.mixer.Sound(path.join(snd_dir, snd)))
i would like to mute all items in the list individually instead of muting the entire application or mixer. I tried the following:
for i in expl_sounds:
expl_sounds[i].set_volume(Sound_Volume)
TypeError: list indices must be integers or slices, not Sound
I dont get the error message. The i in the loop is an integer and the mixer.set_Volume is a valid operation for the elements
What would be the correct way to iterate and apply the volume to each element ?
Your error comes from your misunderstanding of the syntax for i in expl_sounds. The i in the loop is an integer isn't true, i is one element of the expl_sounds, a pygame.mixer.Sound instance that you just add before
So use the object directly
for sound in expl_sounds:
sound.set_volume(Sound_Volume)
To do it by indices, do
for i in range(len(expl_sounds)):
expl_sounds[i].set_volume(Sound_Volume)
When you write for i in expl_sounds:, you are iterating on the elements in expl_sounds, so you can just do:
for i in expl_sounds:
i.set_volume(Sound_Volume)
The "i" in "for i in expl_sounds" is the sound object itself, not the array index.
Try the following:
for i in expl_sounds:
i.set_volume(Sound_Volume)

Python list of indexes

I would like to get the indexes of a given list (images) and put it into a list.
So far I've tried:
list(images)
But this only returns itself.
list(images.keys())
But this gives me an error that images has no attribute keys
Is there a way to get all the indexes into its own list?
You could simply create a range as long as the list:
range(len(images))
This returns Range object, which is usable in most of the same contexts as a list. If you really wanted it as a list however, you could just put the range in a list:
list(range(len(images)))

Python list.remove items present in second list

I've searched around and most of the errors I see are when people are trying to iterate over a list and modify it at the same time. In my case, I am trying to take one list, and remove items from that list that are present in a second list.
import pymysql
schemaOnly = ["table1", "table2", "table6", "table9"]
db = pymysql.connect(my connection stuff)
tables = db.cursor()
tables.execute("SHOW TABLES")
tablesTuple = tables.fetchall()
tablesList = []
# I do this because there is no way to remove items from a tuple
# which is what I get back from tables.fetchall
for item in tablesTuple:
tablesList.append(item)
for schemaTable in schemaOnly:
tablesList.remove(schemaTable)
When I put various print statements in the code, everything looks like proper and like it is going to work. But when it gets to the actual tablesList.remove(schemaTable) I get the dreaded ValueError: list.remove(x): x not in list.
If there is a better way to do this I am open to ideas. It just seemed logical to me to iterate through the list and remove items.
Thanks in advance!
** Edit **
Everyone in the comments and the first answer is correct. The reason this is failing is because the conversion from a Tuple to a list is creating a very badly formatted list. Hence there is nothing that matches when trying to remove items in the next loop. The solution to this issue was to take the first item from each Tuple and put those into a list like so: tablesList = [x[0] for x in tablesTuple] . Once I did this the second loop worked and the table names were correctly removed.
Thanks for pointing me in the right direction!
I assume that fetchall returns tuples, one for each database row matched.
Now the problem is that the elements in tablesList are tuples, whereas schemaTable contains strings. Python does not consider these to be equal.
Thus when you attempt to call remove on tablesList with a string from schemaTable, Python cannot find any such value.
You need to inspect the values in tablesList and find a way convert them to a strings. I suspect it would be by simply taking the first element out of the tuple, but I do not have a mySQL database at hand so I cannot test that.
Regarding your question, if there is a better way to do this: Yes.
Instead of adding items to the list, and then removing them, you can append only the items that you want. For example:
for item in tablesTuple:
if item not in schemaOnly:
tablesList.append(item)
Also, schemaOnly can be written as a set, to improve search complexity from O(n) to O(1):
schemaOnly = {"table1", "table2", "table6", "table9"}
This will only be meaningful with big lists, but in my experience it's useful semantically.
And finally, you can write the whole thing in one list comprehension:
tablesList = [item for item in tablesTuple if item not in schemaOnly]
And if you don't need to keep repetitions (or if there aren't any in the first place), you can also do this:
tablesSet = set(tablesTuple) - schemaOnly
Which is also has the best big-O complexity of all these variations.

Contain Output in a List

For my below code everything is working correctly, however I am trying to store my output in a list and I can't figure out how to do so. I tried to create an empty list and append the output to that list but it did not work. Any help would be great!
sample_photo_rep["photo"]["tags"]["tag"]
for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]:
print [sample_tags_list['raw'].decode('utf-8')]
current output:
[u'Nature']
[u'Mist']
[u'Mountain']
correct output: [u'nature', u'mist', u'mountain']
In each loop, you're printing a list containing a single element, i.e. [u'Nature'], [u'Mountain'], etc.
If you remove the enclosing braces, i.e. [sample_tags_list['raw'].decode('utf-8')] to sample_tags_list['raw'].decode('utf-8'), you should just get the string.
Not sure why your append didn't work, as
output = []
for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]:
output.append(sample_tags_list['raw'].decode('utf-8'))
should do the trick. A list comprehension would accomplish the same thing as in the answer from #abccd; both give the same output.
declare an empty list at the top of your code like this:
tags = []
Then, instead of printing it out in your for loop append it to the list:
for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]:
tags.append([sample_tags_list['raw'].decode('utf-8')])
Then tags should be this:
[u'nature', u'mist', u'mountain']
Further Reading
Info on appending to lists: https://www.tutorialspoint.com/python/list_append.htm
Info on lists in general:
https://developers.google.com/edu/python/lists
You can always use list comprehension like this:
print [sample_tags_list['raw'].decode('utf-8') for sample_tags_list in sample_photo_rep["photo"]["tags"]["tag"]]
In place of your for loop. This is by far still the most preferred way of doing this. You can see the pydoc for a simple example of using list comps.

List comprehension in Python?

I have this list :
a = [1,2,3,4,5]
I want to delete each element from the list. This is how I'm doing.
for i in range(0,len(a)):
del a[0]
Can I use list comprehension in this? such as del a[0] for i in range(0,len(a))
List comprehensions are for creating lists, not destroying them. They are not the right tool for this job.
If you want to clear the contents of a list, the quickest way is
del a[:]
This is a slice deletion. The omitted beginning and ending points default to the start and end of the list.
Note that frequently, it's better to just replace the list with a new one:
a = []
This works even if a didn't already exist, and modifications to the new list won't interfere with any other parts of the code that needed the old list. These attributes are often, though not always, desirable.
You wouldn't usually do this with a loop at all. To clear an existing list, use a[:] = [].
No, you cannot del components in a list comprehension. Why would you want to do that in the first place? A list comprehension is for creating a list, not for modifying.
You can replace the list with a different one created with a list comprehension.
The reason is that a list comprehension needs an expression. But del is a statement.
List comprehension (coming from functional programming, where nothing is ever mutated) is for building lists. Since it appears you want to clear out the elements of an existing list (and not creating a new list with only some of the elements etc.), list comprehension is not the right tool.
That said, list comprehension can be abused to do it:
[a.pop() for i in range(len(a))]
NOTE: This is a bad idea (since it uses list comprehenstion for something completely different than what it is intended for) and I would strongly recommend you do not use it.

Categories