List comprehension in Python? - 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.

Related

writing for loop into list comprehension

I have written a for loop but want to implement it as list comprehension. Followed the usual guides for translating it to a list comprehension, but for some reason the for loop is working but the list comprehension isn't
Below is both my for loop as well as the list comprehension code. Note that "tipos" is a series and "airbnb" a dataframe (though that should not be relevant, I think.
for i in range(len(tipos)):
porcentajes.append(tipos[i]/airbnb.room_type.count()*100)
porcentajes
porcentajes=[porcentajes.append(tipos[i]/airbnb.room_type.count()*100) for i in range(len(tipos))]
porcentajes
Using the for loop I get the list I want, but using the list comprehension I get a list full of Nones. I'd be expecting to get the same result as with the for loop. How do I correct the list comprehension?
I think what you want is actually:
porcentajes=[(tipos[i]/airbnb.room_type.count()*100) for i in range(len(tipos))]
(no need to append... you're creating the list by doing the comprehension)
However, I'm not sure why you need the index either, you can likely just loop over the items:
porcentajes=[(t/airbnb.room_type.count()*100) for t in tipos]

How to get a set of outputs of a command to use them one by one later

This is what I am trying to achieve while using Sage worksheet interface.
Assume that I wrote a code and it gave, for example, for each i in a range of lists, list[0]. (First element of each list)
So I have multiple outputs.
Now I want to use these outputs, consider them as a list, and take iterative combinations of elements of it.
Can I do that, and how?
Probably it is easiest to make a new list out of this.
for list in list_of_lists:
list[0]
could become (I'm making a minimal change to your code)
new_list = []
for ls in list_of_lists:
new_list.append(ls[0])
and then new_list should have what you want. (For more concise ways to do this, learn about Python list comprehensions.)
I did this for L a list of lists and lf = len(L) and it worked.
liste = [list(L[i])[0] for i in range (1,lf)]
for (f1,f2,f3) in Combinations(liste,3):
..

Python inserting lists into a list with given length of the list

My problem is, that need a list with length of 6:
list=[[],[],[],[],[],[]]
Ok, that's not difficult. Next I'm going to insert integers into the list:
list=[[60],[47],[0],[47],[],[]]
Here comes the real problem: How can I now extend the lists and fill them again and so on, so that it looks something like that:
list=[[60,47,13],[47,13,8],[1,3,1],[13,8,5],[],[]]
I can't find a solution, because at the beginning i do not know the length of each list, I know, they are all the same, but I'm not able to say what length exactly they will have at the end, so I'm forced to add an element to each of these lists, but for some reason i can't.
Btw: This is not a homework, it's part of a private project :)
You don't. You use normal list operations to add elements.
L[0].append(47)
Don't use the name list for your variable it conflicts with the built-in function list()
my_list = [[],[],[],[],[],[]]
my_list[0].append(60)
my_list[1].append(47)
my_list[2].append(0)
my_list[3].append(47)
print my_list # prints [[60],[47],[0],[47],[],[]]

Python Sequence Syntax

I am new to python and was reading through some code for a Sublime Text plugin and came across some code I am not familiar with.
views = [v for v in sublime.active_window().views()]
it is the "[v for v" part that I don't understand. What in the heck is this piece of code doing?
Thanks in advance!
That's a list comprehension. It is equivalent to (but more efficient than):
views = []
for v in sublime.active_window().views():
views.append(v)
Note that in this case, they should have just used list:
views = list(sublime.active_window().views())
There are other types of comprehensions that were introduced in python2.7:
set comprehension:
{x for x in iterable}
and dict comprehension:
{k:v for k,v in iterable_that_yields_2_tuples}
So, this is an inefficient way to create a dictionary where all the values are 1:
{k:1 for k in ("foo","bar","baz")}
Finally, python also supports generator expressions (they're available in python2.6 at least -- I'm not sure when they were introduced):
(x for x in iterable)
This works like a list comprehension, but it returns an iterable object. generators aren't particularly useful until you actually iterate over them. The advantage is that a generator calculates the values on the fly (rather than storing the values in a list which you can then iterate over later). They're more memory efficient, but they execute slower than list-comps in some circumstances -- In others, they outshine list-comprehensions because it's easy to say -- Just give me the first 3 elements please -- whereas with a list comprehension, you'd have to calculate all the elements up front which is sometimes an expensive procedure.
This is a list comprehension. It's a bit like an expression with an inline for loop, used to create a quick list on the fly. In this case, it's creating a shallow copy of the list returned by sublime.active_window().views().
List comprehensions really shine when you need to transform each value. For example, here's a quick list comprehension to get the first ten perfect squares:
[x*x for x in range(1,11)]

Parsing indeterminate amount of data into a python tuple

I have a config file that contains a list of strings. I need to read these strings in order and store them in memory and I'm going to be iterating over them many times when certain events take place. Since once they're read from the file I don't need to add or modify the list, a tuple seems like the most appropriate data structure.
However, I'm a little confused on the best way to first construct the tuple since it's immutable. Should I parse them into a list then put them in a tuple? Is that wasteful? Is there a way to get them into a tuple first without the overhead of copying/destroying the tuple every time I add a new element.
As you said, you're going to read the data gradually - so a tuple isn't a good idea after all, as it's immutable.
Is there a reason for not using a simple list for holding the strings?
Since your data is changing, I am not sure you need a tuple. A list should do fine.
Look at the following which should provide you further information. Assigning a tuple is much faster than assigning a list. But if you are trying to modify elements every now and then then creating a tuple may not make more sense.
Are tuples more efficient than lists in Python?
I wouldn't worry about the overhead of first creating a list and then a tuple from that list. My guess is that the overhead will turn out to be negligible if you measure it.
On the other hand, I would stick with the list and iterate over that instead of creating a tuple. Tuples should be used for struct like data and list for lists of data, which is what your data sounds like to me.
with open("config") as infile:
config = tuple(infile)
You may want to try using chained generators to create your tuple. You can use the generators to perform multiple filtering and transformation operations on your input without creating intermediate lists. All of the generator processing is delayed until iteration. In the example below the processing/iteration all happens on the last line.
Like so:
f = open('settings.cfg')
step1 = (tuple(i.strip() for i in l.split(':', 1)) for l in f if len(l) > 2 and ':' in l)
step2 = ((l[0], ',' in l[1] and 'Tag' in l[0] and l[1].split(',') or l[1]) for l in step1)
t = tuple(step2)

Categories