A.P
A.P

Reputation: 5

How to pull a value out of a parentheses

I have a list:

[(1,3),(2,4)]

How can I pull just the values 1 and 2 from both the elements from the list. to my knowledge I cannot index as the values are in parentheses.

Upvotes: 0

Views: 70

Answers (4)

gelonida
gelonida

Reputation: 5630

you might want to read some basic documentation / tutorials about python, in particular about lists and tuples. (see links at the end of my answer)

If

l = [(1,3),(2,4)]

then l is a list with two members, each member is a tuple with two members.

You can get the 1 with l[0][0] and the 2 with l[1][0]

l[0] would yield the tuple (1, 3)

if you want to get the 1 and the 2 in one line you might look at the documentation of the zip function.

one, two = next(zip(*l))

or you do it explicitly with:

one, two = l[0][0], l[1][0]

Relevant links:

Upvotes: 1

daniel-eh
daniel-eh

Reputation: 414

So I would give this list a name, something like:

pairs_list = [(1, 3), (2, 4)]

Then you can access them using the indices. So:

print(pairs_list[0][0])
print(pairs_list[1][0])

Basically what's happening here is you want to access the first pair, at 0th index, and the first number, at that pair's 0th index. Then the second list, at the 1st index, and its first number, at the 0th index.

Or as the other commenter suggested, you can assign these values to a variable and print the variables. Like:

first_num = pairs_list[0][0]
second_num = pairs_list[1][0]

Then you just print those two variables.

Upvotes: 0

Teejay Bruno
Teejay Bruno

Reputation: 2159

You can still index, the tuples are referred to what's called nested.

As for code, to access them you could write:

vals = [(1,3),(2,4)]

val1, val2 = vals[0][0], vals[1][0]

Upvotes: 0

Ted Brownlow
Ted Brownlow

Reputation: 1117

my_list = [(1,3),(2,4)]

just_first = [pair[0] for pair in my_list]

You can index the values using 2 indices. The index for '1' in your example is [0][0] and the index for '2' is [1][0]

Upvotes: 0

Related Questions