#Python List is written as set of comma separated values surrounded by squared brackets #Lists may contain items of different data types, but usually all items will be of the same type #Lists can be indexed and sliced #Lists can be concatenated #Lists are Mutable i.e. their contents can be appended #Use the .append() method to add items to the end of the list #Use the len() function to return the length of a list #EXAMPLE OF A LIST numbers = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] print numbers #EXAMPLE 2 fruits = ['apple', 'berry', 'cherry', 'grape'] print fruits #INDEXING AND SLICING LISTS print numbers[0],',',numbers[-1] #indexed: returns the first and last items respectively in the list print fruits[0],',',fruits[-1] #indexeed: returns the last item in the list print numbers[:6] #sliced: returns items 0 to 5 in the list print numbers[6:] #sliced: returns items 6 to to the last in the list #CONCATENATION basket = numbers + fruits print basket basket2 = numbers[:3] + fruits[2:] print basket2 #MUTABLE print 'This is an example of the mutable nature of Lists' print fruits[1] fruits[1] = 'banana' #adding a new value to list index 1 print fruits[1],',', 'berry was replaced with banana' print fruits #append() method and len() function fruits.append('orange') #.append() adds an item to the end of the list print fruits print len(fruits) #len() returns the length or number of items in the list
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question