How can I get specific elements from a tuple/list in Python without iterating?

  • Context: Python 
  • Thread starter Thread starter Punkyc7
  • Start date Start date
  • Tags Tags
    Database Python
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 2K views
Punkyc7
Messages
415
Reaction score
0
I am using python to get tuples from a db.

I am doing

cur.execute("Select Statement");

I use cur.fetchall to get the tuples.

My question is how do you iterate over the returned tuples and store the columns into an array? I want to iterate over n tuples, not all the returned results. Is storing the results into an array necessary or is the returned tuple considered an or a list?


Thanks for the help!
 
Physics news on Phys.org
Punkyc7 said:
I am using python to get tuples from a db.

I am doing

cur.execute("Select Statement");

I use cur.fetchall to get the tuples.

My question is how do you iterate over the returned tuples and store the columns into an array? I want to iterate over n tuples, not all the returned results. Is storing the results into an array necessary or is the returned tuple considered an or a list?


Thanks for the help!

The only real difference between a tuple and a list is that tuples are not mutable (changeable). Lists are. They are both iterable. If you really want to change them you can change a tuple t into a list l with l=list(t).
 
Ok so if the select statement returns 50 tuples that are of type (int, String) and say I only wanted 5 of them, would I have to iterate over the cur or Is there a way to just get the first 5?

Sorry if this is a stupid question, I am just getting into python.
 
Punkyc7 said:
Ok so if the select statement returns 50 tuples that are of type (int, String) and say I only wanted 5 of them, would I have to iterate over the cur or Is there a way to just get the first 5?

Sorry if this is a stupid question, I am just getting into python.

It's not stupid. No, to get the first five elements of a tuple/list t into a tuple/list s, say s=t[:5]. Look up the way Python handles subrange indexing. It's really quite neat. You don't have to iterate to do something like that.