Lists
- A list is a sequence of values.
- [ and ]
- like numerically indexed arrays in PHP
>>> # a list of numbers >>> my_numbers = [10, 15, 20, 25] >>> print my_numbers [10, 15, 20, 25] >>> >>> #a list of strings >>> my_strings = ['Wenbert', 'Programming', 'Address'] >>> print my_strings ['Wenbert', 'Programming', 'Address'] >>> >>> # a list within a list >>> nested = ['Wenbert', ['PHP','Python','Javascript'], 'Philippines'] >>> print nested, my_numbers >>> ['Wenbert', ['PHP','Python','Javascript'], 'Philippines'] [10, 15, 20, 25] >>> >>> #Check if "PHP" is in "nested" list >>> 'PHP' in nested True >>> 'Java' in nested False |
To traverse a list:
for item in nested: print item |
Slicing a list:
>>> basket = ['apples', 'mangoes', 'guava', 'grapes'] >>> basket[2:4] ['guava', 'grapes'] |
You can append to a list:
>>> basket = ['apples', 'mangoes', 'guava', 'grapes'] >>> basket.append('banana') >>> print basket ['apples', 'mangoes', 'guava', 'grapes', 'banana'] |
You can sort a list:
>>> basket = ['apples', 'mangoes', 'guava', 'grapes'] >>> basket.sort() >>> print basket ['apples', 'grapes', 'guava', 'mangoes'] |
You can “pop”, “delete” and “remove” from a list.
>>> basket = ['apples', 'mangoes', 'guava', 'grapes'] >>> >>> basket.pop() 'grapes' >>> print basket ['apples', 'mangoes', 'guava'] >>> >>> basket.remove('mangoes') >>> print basket ['apples', 'guava'] >>> >>> del basket[0] >>> print basket ['guava'] |
Spliting and Joining:
>>> string = 'Wenbert Del Rosario' >>> pieces = string.split() >>> print pieces ['Wenbert', 'Del', 'Rosario'] >>> >>> bag = 'healing potion | dagger | round shield |gold' >>> items = bag.split(' | ') >>> print items ['healing potion', 'dagger', 'round shield |gold'] >>> ">".join(items) #glue items together with the ">" symbol 'healing potion>dagger>round shield |gold' |
That’s about it. If I encounter more, I will update this post.
How can we pop from the list? I understood everything else except this. Can you help please?
.pop() just returns the last value and then removes it from the list.
For example: