How do i use lists in python?
-
A list is like a shopping list you make when you go shopping.
Create a list. The count starts from zero.
>>> fruits = [ "bannanas", "coconuts", "pineapple"]
Print the first element (first entry) in the list.
>>> print(fruits[0]) bannanas
Print the second element in the list.
>>> print(fruits[1]) coconuts
Change the value of an element in the list. Here we change the second item in the list from coconuts to melons.
>>> fruits[1] = "melons" >>> print(fruits) ['bannanas', 'melons', 'pineapple']
Print the number of items in our list.
>>> length = len(fruits) >>> print(length) 3
Add another item to the list.
>>> fruits.append("figs") >>> print(fruits) ['bannanas', 'melons', 'pineapple', 'figs']
Insert another item into the list in a specific place.
>>> fruits.insert(2, "coconuts") >>> print(fruits) ['bannanas', 'melons', 'coconuts', 'pineapple', 'figs']
Print the index number of the item.
>>> mybestfruit = fruits.index("melons") >>> print(mybestfruit) 1
Remove the last item from a list.
>>> print(fruits) ['bannanas', 'melons', 'coconuts', 'pineapple'] >>> fruits.pop() 'pineapple' >>> print(fruits) ['bannanas', 'melons', 'coconuts']
Sort a list alphabetically.
Print the current order of the list.>>> print(fruits) ['bannanas', 'melons', 'coconuts']
Order after running the sort method.
>>> fruits.sort() >>> print(fruits) ['bannanas', 'coconuts', 'melons']
Let's remove coconuts from the list.
>>> fruits.remove("coconuts") >>> print(fruits) ['bannanas', 'melons']
© Lightnetics 2024