Mehdi Rezzag Hebla
Mehdi Rezzag Hebla

Reputation: 334

Python printing the first item of each nested list with a single print command

I would like to know why does this code does not output the first item of each nested list. I have found an alternative that works but I would like to know why this one does not output the desired output.

tableData = [
['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'], 
['dogs', 'cats', 'moose', 'goose']]
print(tableData[:][1])

Upvotes: 0

Views: 80

Answers (7)

Barel elbaz
Barel elbaz

Reputation: 656

[ from: to] operator means slicing - > returns new string.

For example:

lst = [0, 1, 2, 3] 
lst[0:2] #will return [0, 1]

[ : ] will return the list as it is.

So if you want to access the first value type: lst[0] In your code you typed tableData[1] so it returns the second index because the indexes starts from Zero

Upvotes: 0

Zack Turner
Zack Turner

Reputation: 226

You should use [0] this will get the first element in the list then you do a for loop to go through every element in the list for example:

tableData = [
['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'], 
['dogs', 'cats', 'moose', 'goose']]
for i in tableData:
    print(i[0])

I hope this makes sense.

Upvotes: 1

emnoor
emnoor

Reputation: 2708

Because tableData[:] means the whole list, which is just a copy of tableData. So tableData[:][1] is the 1-th (second) item in tableData, which is ['Alice', 'Bob', 'Carol', 'David'] in your code.

Upvotes: 1

Josh Clark
Josh Clark

Reputation: 1012

tableData[:] returns the entire list. So tableData[:][1] only returns the second element in tableData, which is your list ['Alice', 'Bob', ...].

You can get the first element of every list using a list comprehension:

print [sublist[0] for sublist in tableData]

The above code is equivalent to this:

first_elements = []
for sublist in tableData:
    first_elements.append(sublist[0])
print first_elements

Upvotes: 1

CrazyPythonProgrammer
CrazyPythonProgrammer

Reputation: 1327

here is the code for this which gives clean space seperated output print(*[i[0] for i in tableData]) In Your the tableData[:] will evaluate to TableData then TableData[1] will evaluate to ['Alice', 'Bob', 'Carol', 'David']

Upvotes: 0

Lilian Vault
Lilian Vault

Reputation: 486

This doesn't work because tableData[:] returns the whole list. It's an equivalent of tableData (without [:]). As posted Josh, you can use a list comprehension to get the elements you want.

Upvotes: 1

Kumar Sanu
Kumar Sanu

Reputation: 226

print([i[0] for i in tableData])

Upvotes: 0

Related Questions