Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access List elements

Tags:

python

list

I have a list

list = [['vegas','London'],['US','UK']] 

How to access each element of this list?

like image 943
user1389673 Avatar asked May 16 '12 06:05

user1389673


People also ask

How do you access the elements of a list?

The syntax for accessing the elements of a list is the same as the syntax for accessing the characters of a string. We use the index operator ( [] – not to be confused with an empty list). The expression inside the brackets specifies the index. Remember that the indices start at 0.

How do we access elements from a list in Python?

Python has a great built-in list type named "list". List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0.

How do I get the list element in R?

Accessing List Elements. Elements of the list can be accessed by the index of the element in the list. In case of named lists it can also be accessed using the names.


2 Answers

I'd start by not calling it list, since that's the name of the constructor for Python's built in list type.

But once you've renamed it to cities or something, you'd do:

print(cities[0][0], cities[1][0]) print(cities[0][1], cities[1][1]) 
like image 129
sblom Avatar answered Sep 23 '22 06:09

sblom


It's simple

y = [['vegas','London'],['US','UK']]  for x in y:     for a in x:         print(a) 
like image 42
AutomationNerd Avatar answered Sep 22 '22 06:09

AutomationNerd