9. Python Lists


List is one of python data types which defined with comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type. Example
mix_type_list = [123, 34.5, 'This is string', 23 + 9j]  
text_editors = ['notepad++', 'sublime text', 'notepad']  
print(mix_type_list)  
print(text_editors) 

9.1 Accessing List Values

Like string, list can be indexed and sliced. You can slice list with this expression list_name[start_index:end_index:step].
subjects = ['math', 'biology', 'chemistry']
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
words = ['Python', 'is', 'awesome', 'yeah']

print('subjects[0]:', subjects[0]);     # indexing
print('numbers[2:5]:', numbers[2:5])    # slicing
print('numbers[::2]:', numbers[::2])    # by default start index is 0 and end index is the length of list
print('numbers[2:7:2]', numbers[2:7:2]) 
print('words[-2]:', words[-2:])         # negative index count from the right
print('numbers[:]:', numbers[:])

9.2 Update the List

Unlike string, list is mutable, it's possible to change their element.
subjects = ['math', 'biology', 'chemistry']
words = ['Python', 'is', 'awesome', 'yeah']

subjects[2] = 'Physics'
words[2] = 'amazing' 
print(subjects)
print(words)
You can update the slice of the list, change their size or even clear it entirely.
squares = [1, 4, 9, 16, 5, 6, 9, 64, 81] # something is wrong
squares[4:7] = [25, 36, 49]              # replace the right value
print(squares) 

squares[:2] = []                         # remove some 
print(squares)

squares[:] = []                          # clear it entirely
print(squares)

squares = [1, 4, 9, 16]
squares = []                             # you can actually do this too
print(squares)
You can delete the an element or a slice from list using del keyword.
subject = ['math', 'biologi', 'chemistry', 'algebra', 'computer science']

del subject[1] # delete biologi
print(subject)

del subject[1:3] # delete chemisty and algebra 
print(subject)

del subject[:] # delete all items
# del subject     # or do this instead

9.3 List Operations

Some operations that you can do with list are concatenation, repetition, membership, identity, and iterate over the list.

>>> [1, 2, 3] + [4, 5, 6]	# concatenation
[1, 2, 3, 4, 5, 6]
>>> ['Hello'] * 3 		# repetition
['Hello', 'Hello', 'Hello']
>>> 1 in [1, 2, 3] 		# membership operator
True
>>> [1, 3, 4] is not [1, 3, 4]	# identity operator
True
>>> for elmt in [1, 2, 3]:	# iterate the list
	print(elmt)

	
1
2
3

That's all brief introduction about Python list, if you guys have any questions please give comments.

Subscribe to receive free email updates:

0 Response to "9. Python Lists"

Post a Comment