Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create an empty list of tuples?

I'm trying to create a new empty list that will contain tuples when calling extend. Here's where I declare the list:

ticketData = list()

And I loop through another list to add tuples to this list:

data = (0, requestor, subject, thetime)
ticketData.extend(data)

When I output the result it shows this:

[0, 'Name', 'Test Subject', '03:31:12']

I need it to be a list of tuples, not just a list so that I can use sqlite's executemany function.

It seems straight forward, but I haven't been able to find an answer on here. Thanks!

like image 462
corym Avatar asked May 23 '15 02:05

corym


2 Answers

Just append it to the list, so that the tuple will be added instead of having the elements of the tuple extend the list.

ticketData.append(data)

will add data to the list ticketData

like image 122
Eric Renouf Avatar answered Oct 11 '22 08:10

Eric Renouf


Although this question has been answered already, I thought it could be useful to know about how to construct an iterable that should contain an empty iterable. In Python, constructors like list(), set(), tuple() etc. take an iterable as input. Hence they iterate through the iterable and somthing like list(tuple()) does not return a list with an empty tuple. Instead the list constructor iterates through the tuples, and since it has no items in it it results in an empty list.

To construct a list that contains an empty tuple do the following:

Instead of my_list = list(tuple()) // returns [] or list()

Do: my_list = [tuple()]

Or: my_list = list([tuple()]) //constructor iterates through the list containing the empty tuple

Analogously, if you want to make a set containing an empty tuple do the following:

Instead of my_set = set(tuple()) // returns set()

Do: my_set = {tuple()}

Or: my_set = set([tuple()]) // constructor iterates through the list, containing the empty tuple

This also applies to other iterables. I am writing this, because I myself have had problems using these constructors to return e.g. a list containing another empty iterable.

like image 4
El Sholz Avatar answered Oct 11 '22 10:10

El Sholz