Sie sind auf Seite 1von 3

Identify the difference between append() and extend()

Try:

Tutorial 3 - List, String - II, Files I/O


fruits = ["apple", "banana", "carrot"]
fruits.append(['lemon', 'mango'])
Jiaming Xie - 115020147 *The grey part of this note is optional.
print(fruits)
fruits.extend(['lemon', 'mango'])
print(fruits)
In Python, lists are a versatile datatype that can contain multiple different data types within the
same square brackets. The data types include numbers, strings, other objects, and even other
.append() : Adds its argument as a single element to the end of a list. The length of the list
lists.
increases by one.
Lists are defined using square brackets [ ] containing a comma separated list of values.
.extend() : Iterates over its argument and adding each element to the list and extending the

Advanced data type - List list. The length of the list increases by number of elements in it’s argument.

Indexing
List is a versatile data type. It can contain multiple values with different data types.
For each item in a list, its position is represented by its index.
*What is a "method"?
Python has similar indexing rules with C++, where the indices starts from 0. The last element of
Method is a function defined under a class or an object. a list is index (len - 1)

A list is an object in python and we can apply some "method" to it. In Python, indices can also be used as negative numbers, which means the placement from the
end of a list. The last element of a list can also be located with index -1, the second-to-last can
How to use a method?
be located -2 and so on.
1. Create an instance of that object
Note: Be careful with the 'index out of range' error. For a list of length LEN, the available
2. format: list.method() indexing domain is [-LEN, LEN - 1].

Examples Example

Declaration names = ['Alice', 'Bob', 'Cindy', 'Damon']


print(len(names)) # the length of names is 4
primes = [2, 3, 5, 7, 11] print(names[0]) # 'Alice'
fruits = ["apple", "banana", "carrot"] print(names[3]) # 'Damon'
student = ["Jane", 19, 'SME', 'CUHK(SZ)'] print(names[-1]) # 'Damon'
empty_list = [] print(names[-4]) # 'Alice'

Useful methods for list print(names[4]) # IndexError: list index out of range
print(names[-5])

fruits.append('durian') # ["apple", "banana", "carrot",


"durian"] Slicing
fruits.extend(['lemon', 'mango']) # ["apple", "banana", "carrot",
"durian", "lemon", "mango"] A slice, or sub-list of Python list elements can be selected from a list using a colon-separated
fruits.remove('carrot') # ["apple", "banana", "durian", starting and ending point.
"lemon", "mango"]
The syntax is list_name[START_INDEX : END_INDEX] . The slice will include the item with
fruits.insert(2, 'cherry') # ["apple", "banana", "cherry",
"durian", "lemon", "mango"] START_INDEX and everything until but excluding the END_INDEX item.
The START_INDEX and END_INDEX can be left blank, which will be treated as the 0 and
s = 'database'
len(list) respectively.
# start:end
The slicing syntax has also supported an optinal third STEP argument. Like
print(s[0]) # 'd'
list_name[START_INDEX : END_INDEX : STEP] . The STEP argument allow us to set how
print(s[-1]) # 'e'
the list's index will increment between the indexes that we have set.
print(s[:4]) # 'data'
When slicing a list, a new list is returned, so if the slice is saved and then altered, the original list print(s[-4:]) # 'base'

remains the same.


# start:end:step
Example print(s[1:6:2])# 'aaa'
print(s[::4]) # 'db'
print(s[::-1]) # 'esabatad'
p = [0, 1, 2, 3, 4, 5]

# start:end
I/O files
print(p[2:4]) # [2, 3]
print(p[:4]) # [0, 1, 2, 3]
Built-in open() function:
print(p[2:]) # [2, 3, 4, 5]
print(p[2:-2]) # [2, 3] To open a file for writing, use the built-in open() function. open() returns a file object, and is
most commonly used with two arguments.
# start:end:step
print(p[1:5:2]) # [1, 3]
file_object = open(filename, mode)
print(p[0::2]) # [0, 2, 4]
print(p[1::2]) # [1, 3, 5]
The mode can be:
print(p[4:0:-1]) # [4, 3, 2, 1]
'r' when the file will only be read
print(p[::-1]) # [5, 4, 3, 2, 1, 0]
'pointer' stays at the beginning of the file.
'w' for only writing (an existing file with the same name will be erased)
If you want to avoid the problem of list index out of range, you can utilize len() .
File existing: cover the file with your input
lst = ['ser','wer','wt4','rw34','ewr','ewr3','dse','t4','se'] File not existing: creat a new file
for i in range(0,len(lst)): #range(0,n)=[0,1,2, ... , n-1] 'a' opens the file for appending; any data written to the file is automatically added to
print(lst[i]) the end

'pointer' stays at the end of the file.


Advanced data type - More about strings 'r+' opens the file for both reading and writing

'pointer' stays at the beginning of the file.


String has the similar properties as List. It can also be indexing and slicing with the similar
syntax. Create a new file
Example
file = open('onefile.txt','w')
file.write('I am a student.\n')
file.write('I am in my 4th year in college.')
file.write('I am doing good.')
file.close()

Notes:

\n means a new line


Remember to close the file in the end.
file = open('onefile.txt','a')
file.write('\n Here I am.\n')
Read a file #The pointer will start in the end of the file, so you need to add '\n'
here,
file = open('onefile.txt','r') #or your new line will start at the end of onefile.txt
file.write('Hello world.\n')
print(file.read()) # show all the file file.close()
print(file.read(10)) # show the first ten characters

Loop over a file object


print(file.readline()) # view by line
print(file.readlines()) # view all lines
file.close()
file = open('onefile.txt','r')
for line in file:
Every time you read a line, the pointer will move to the next line.
print(line)
file.readline() : read by line file.close()

file.readlines() : read by line and put each line into a list.


File path *
You man be confused about why it prints nothing after print(file.read()) . It is because the
pointer goes to the end of the file. You can also specify file names using absolute paths.

You can refresh the position of the pointer to the beginning with file.seek(0) .
# in Mac/Linux:
Example: open('/etc/file/onefile')
# or in Windows:
file = open('Poem.txt','r') open('C:\Users\user\Desktop\onefile.txt')

print(file.read()) You can use terminal to find the absolute path of a file.
file.seek(0)
print('------------')
If your file is in the same folder with your code file, you can use relative paths.
print(file.read(10))
print('------------') Read CSV or EXCEL file
print(file.readline())
Here you need to import a module called pandas .
print(file.readline())
print('-------------')
print(file.readlines()) import pandas as pd
print('-------------') file1 = pd.read_csv('spreadsheet.csv')
file.seek(0) file2 = pd.read_excel('spreadsheets.xlsx')
for i in file.readlines(): # read by line and put each line into a list
print(i)

Append a file

Das könnte Ihnen auch gefallen