I have a list
list = [['vegas','London'],['US','UK']]
How to access each element of this 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.
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.
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.
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])
It's simple
y = [['vegas','London'],['US','UK']] for x in y: for a in x: print(a)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With