Leo
Leo

Reputation: 898

How to extract a string from a list

I'm new to Python without any programming background except for some shell scripting.

I want to extract 2 fields from the below list: Here I want 'title' and 'plays' and assign it to a another list eg) new_list=[title,plays]

alist=[(0, 'title', 'TEXT', 0, None, 0), (1, 'plays', 'integer', 0, None, 0)]

Upvotes: 0

Views: 122

Answers (2)

caldera.sac
caldera.sac

Reputation: 5088

alist = [(0, 'title', 'TEXT', 0, None, 0),(0, 'plays', 'integer', 0, None, 0)]
new_list = [alist[0][1], alist[1][1]]

to check,

print(new_list)

Explain

This line:

alist = [(0, 'title', 'TEXT', 0, None, 0), (0, 'plays', 'integer', 0, None, 0)]

Above is actually a tuple inside list. So inside the the alist, there are two tuples. Inside each tuple, there are 6 objects.

So alist[0] means, you are calling the first tuple inside the alist. and alist[0][1] means your are calling second element of the first tuple. Like this, you can think about alist[1][1] also.

Upvotes: 2

Robᵩ
Robᵩ

Reputation: 168626

The simplest way, of course, it is just write the assignment statement:

new_list=['title','plays']

But you probably intended to ask a more general question, like "How can I extract the 2nd item from the first two tuples in a list?" Like so:

new_list = [alist[0][1], alist[1][1]]

Or maybe you meant, "How can I extract the 2nd item from each tuple in a list?" Like so:

new_list = [t[1] for t in alist]

Upvotes: 3

Related Questions