0

Every row of my list goes like this:

[(21, ['Rodriguez', 'Lara', 'Vicky', '55302292'])]

and I want it to print just the name, in this case Vicky. The code I use is this

for x in numbers:  
    r=str(x)  
    d1= r.split(',')  
    print ('D1', d1)  

and it prints this:

['[(21', " ['Rodriguez'", " 'Lara'", " 'Vicky'", " '55302292'])]"]
2
  • What has all this to do with CSV files though? Yes, Python list and tuple objects use commas in the syntax to delimit distinct values, but that doesn't make them CSVs. :-) Commented Apr 29, 2015 at 17:53
  • if all of them have same structure, just [(21, ['Rodriguez', 'Lara', 'Vicky', '55302292'])][0][1][2] :) Commented Apr 29, 2015 at 18:35

4 Answers 4

3

Don't turn your perfectly good list into a string! just use indexing:

x[0][1][2]

To illustrate what this does:

>>> x = [(21, ['Rodriguez', 'Lara', 'Vicky', '55302292'])]
>>> x[0]
(21, ['Rodriguez', 'Lara', 'Vicky', '55302292'])
>>> x[0][1]
['Rodriguez', 'Lara', 'Vicky', '55302292']
>>> x[0][1][2]
'Vicky'

Each additional subscription ([...]) drills deeper into the nested structure; x[0] extracts the tuple from the list; x[0][1] then accesses the list value in that tuple (x[0][0] would give you 21), and x[0][1][2] give you back 'Vicky', the third element in that nested list.

Sign up to request clarification or add additional context in comments.

Comments

3

Get the list first, then extract data from it

>>> list = [(21, ['Rodriguez', 'Lara', 'Vicky', '55302292'])]
>>> names = list[0][1] 
>>> names
['Rodriguez', 'Lara', 'Vicky', '55302292']
>>> names[2]
Vicky

Comments

0

Try this:

for x in numbers:
  r=str(x)
  a=r.split(',')
  print (a[3].strip("' "))

Comments

0

You can iterate over your list, while unpacking a tuple in each iteration. This would make it slightly more clean/readable.

>>> x = [(21, ['Rodriguez', 'Lara', 'Vicky', '55302292']), (22, ['Micheal', 'Jackson', 'John', '66302292'])]
>>> for age, details in x:
...     print details[2]
... 
Vicky
John

1 Comment

Maybe you could accompany your answer with some text that explains it :) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.