Python 3 Lists

Lists

  • Data items: do not need to have the same type
  • Creation: Enclose different data items separated by commas in square brackets
list1 = ['Google', 'Runoob', 1997, 2000]
  • Indexing: starts from 0, the second index is 1, and so on.
  • Reverse indexing: starts from the end, the index of the last element is -1, the one before it is -2, and so on.
  • Updating lists:
#!/usr/bin/python3

list = ['Google', 'Runoob', 1997, 2000]

print ("The third element is: ", list[2])
list[2] = 2001
print ("The updated third element is: ", list[2])

list1 = ['Google', 'Runoob', 'Taobao']
list1.append('Baidu')
print ("The updated list is: ", list1)

The output of the above example:

The third element is: 1997

The updated third element is: 2001

The updated list is: [‘Google’, ‘Runoob’, ‘Taobao’, ‘Baidu’]

If you want to add all elements of another list one by one, use extend:

result = []          # Empty list
result.append(7)     # result -> [7]
result.append('cat')  # result -> [7, 'cat']

# Note: Only one element can be added at a time
result.append([1, 2])   # result -> [7, 'cat', [1, 2]]  as a single element

result.extend([3, 4])   # result -> [7, 'cat', [1, 2], 3, 4]

Python 3 Lists | Runoob Tutorial:

https://www.runoob.com/python3/python3-tutorial.html

Leave a Comment