How do you create an empty list of tuples? - python

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!

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

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.

Related

Is there a way to insert values into a list of tuple in Python?

I have a empty list of tuple and I wish to enter values inside that tuple.
The desired output is :
lst = [()] --> lst = [(1,2,'string1','string2',3)]
A tuple is, by definition, unchangable.
You may want to replace that tuple with a new one like this:
lst = [()]
lst[0] = ("item1", "item2")
In this way you are replacing the origina tuple with a new one with the desired items. If the tuple is not empty you can do:
lst[0] = (*lst[0], "new item")
Here you are unpacking the values of the old tuple (*lst[0] is equal to "item1", "item2" in this example) and adding new items.
Note that if you are working with variable data maybe tuple is not the best data structure to use in this case.
you can't, A tuple is a collection that is ordered and immutable.
though, you can create a new tuple with the same name

Nested tuples within lists

I have a list of lists of tuples and am having trouble accessing the values within the tuples.
Note: apologies for the basic nature of this query, but I'm a beginner and it takes me a long time to access simple variables.
E.g:
[[('foo', '-1')],[('bar', '-5'),('baz', '+7')], [('qux', '+9')]]
I want to 1) remove the second value of each tuple i.e. the numbers and 2) remove the tuple type and just convert it a list of strings.
As you can see, it is a list of tuples so it can be one tuple or a number of tuples based on the content of extraction - but it is always 2 values within each tuple and I want to remove the second value.
I am having trouble 1) converting each tuple to a string, to be able to 2) remove the second value (preferably I want to remove that before making it into a string) - any ideas?
Just get 0 index of each tuple by iterating in list
ll_tuple = [[('foo', '-1')],[('bar', '-5'),('baz', '+7')], [('qux', '+9')]]
print(
[
[tuple_[0] for tuple_ in l_tuple]
for l_tuple in ll_tuple
]
)
I don't understand very well the question but two points:
Your values in tuple are already string.
To access tuple, you can iterate over your list and access first value of tuple by doing this:
tuple[0]
I don't understand if you have a list of list of tuple, or a list of tuple
First of all your list of lists of tubles is incorrectly formatted I assume what you mean:
data = [
[('foo', '-1')],
[('bar', '-5')],
[('baz', '+7'), ('qux', '+9')]
]
When create a nested for loop and append the first element in each tuble to new list output.
output = []
for lst in data:
for tub in lst:
output.append(tub[0])
print(output)
Prints:
['foo', 'bar', 'baz', 'qux']

Use a xref of values to sub into tuple based on value - Python

I have a list of xref values
internal_customer = {'01':'11', '03':'33', '05':'55', '07':'77', '08':'88', '06':'66', '09':'22', '11':'18', '12':'19'}
that I would like to use to sub a value in a tuple:
('03', 'S/N A1631703')
So my resulting tuple would be
('33', 'S/N A1631703')
Can someone point me in the direction of the tools I could use to accomplish this?
Unpack and access the dict using the first element, presuming you have an list of tuples:
internal_customer = {'01':'11', '03':'33', '05':'55', '07':'77', '08':'88', '06':'66', '09':'22', '11':'18', '12':'19'}
lst = [('03', 'S/N A1631703'),('05', 'S/N A1631703')]
lst[:] = ((internal_customer[a], b) for a,b in t)
print(t)
tuples are immutable so there is no notion of mutating, you have to create a new tuple comprising of the new value from the dict and the existing second element. The lst[:] syntax at least allows you to modify the original list. You can of course just reassign the name or create a completely new list if you want to maintain the original.

How to append elements inside a list as a list?

I have two lists named queries_fetcher_list and reftable_column_name.
Now I need to perform the operation of taking an element from a and b, and make it as a tuple with zip().
This is the query for doing that:
some_list = []
for i in range (len(reftable_column_name)):
for row in queries_fetcher_list[i]:
some_list.append(dict(zip(reftable_column_name[i], row)))
Now I need that result to be append like this:
[[{first element}], [{second element}]]
What I need to do now is every time when a zip operation is performed that element has to append as a separate list, i.e. list inside a list, like this:
a = []
a = [['one'], ['two'], ['three']]
queries_fetcher_list contains a list of data that are retrived from an MySQL query retrieved with cursor.fetchall().
reftable_column_name is a list contains the column names of a table retrived with cursor.description().
some_list.append([dict(zip(reftable_column_name[i], row))])
will append single-element lists containing your dict.
define a list and everytime when elements got append into it free it, means empty it,now you can achieve what you want,eveytime when an element is appended into a list the list will be flushed and becomes an empty list but make sure to add your elements like this "list(your_element)".

Python: create a list containing dicts

how would you turn this string:
str='ldap:alberthwang,eeid:67739|ldap:meng,eeid:107,building:CL5'
into a list that give you this:
print x[1]['building']=CL5
which would be:
x=[{'ldap':'alberthwang','eeid':'67739'},{'ldap':'meng','eeid':'107','building':'CL5'}]
i've tried to split the string first and append to a list:
sample=[]
for s in str.split('|'):
sample.append(s)
But i'm stuck on how to turn the list items into a dictionary that i can then use to populate another list.
text='ldap:alberthwang,eeid:67739|ldap:meng,eeid:107,building:CL5'
sample=[
dict(item.split(':') for item in part.split(','))
for part in text.split('|')]
print(sample)
# [{'eeid': '67739', 'ldap': 'alberthwang'}, {'building': 'CL5', 'eeid': '107', 'ldap': 'meng'}]
print(sample[1]['building'])
# CL5
List comprehensions are a very convenient way to construct
lists such as this.
A dict can be constructed from an iterable of key-value pairs. The iterable used above was a generator expression.
str is a built-in type, so assigning a string to str overwrites
the builtin. It's better to choose some other variable name to avoid
future surprising bugs.
I read and write list comprehensions backwards:
[ expression # (3)
for variable in # (2)
iterable # (1)
]
(1): First, understand the iterable. In the solution above, this is text.split('|').
(2): for variable in causes variable to be assigned to the values in iterable, one at a time.
(3): Finally, expression can be any Python expression, (usually) using variable.
The syntax for generator expressions is almost the same. The difference between a list comprehension and a generator expression is that a list comprehension returns a list, while a generator expression returns an iterator -- an object that yields its contents on-demand (as it is looped over, or when next is called) instead of generating all the items at once as is the case with lists.
A list can consume a lot of memory if the list is long.
A generator expression will consume less memory (and can even be infinite) because not all elements have to exist in memory at the same time.
Using str as a variable name is a bad idea, since it overshadows the built-in str.
s ='ldap:alberthwang,eeid:67739|ldap:meng,eeid:107,building:CL5'
res = [dict(colonStr.split(':') for colonStr in ds.split(','))
for ds in s.split('|')]
stores the result you what in res.
The key insight here is that dict can take a list of key/value pairs. So, you can do this using a comprehension like this:
string = 'ldap:alberthwang,eeid:67739|ldap:meng,eeid:107,building:CL5'
list_of_dicts = [dict(item.split(':') for item in items.split(',')) for items in string.split('|')]
print list_of_dicts
Maybe this way:
>>> s = 'ldap:alberthwang,eeid:67739|ldap:meng,eeid:107,building:CL5'
>>> x = [dict([d.split(':') for d in ls.split(',')]) for ls in s.split('|')]
>>> x[1]['building']
>>> 'CL5'

Categories

Resources